Hacker News new | ask | show | jobs
by chx 760 days ago
> -x is 2^n - 2^b * k

Erm no. -x is - 2^b * k and it's the "Two's complement" notation which is 2^n - 2 * b * k

This is because the way we generate the "Two's complement" number. Given A in binary representation, let's call A1 the number you get by flipping every bit in A also called one's complement. Observe how every bit in A+A1 is 1 because if the bit was 0 in A then the bit is 1 in A1 and vica versa. So then that's 2^N-1. Two's complement is created by adding 1 to A1 so then A + A1 is 2^N or A1 = 2^N-A. But you do need to prove this before you can use it.

1 comments

The point of two's complement is that it's the same as modulo-2^n arithmetic. In two's complement -x is defined such that x + -x = 0 (mod 2^n); and because x + ~x = 2^n - 1 (mod 2^n), then -x = ~x + 1.

Therefore x & -x works only in two's complement, and it's fair to assume it as the parent comment did.