Reputation: 401
I don't understant why ~x = -x-1 is true. It seems counter-intuitive to me to take the inverse when negating a number. Shouldn't -x just be x with the -/+ bit as 1? Or is this ~x = -x-1 just a hard set rule...
Upvotes: 1
Views: 717
Reputation: 8298
the ~
operator flip all the bits. While -x
is taking the minus of a certain value which is different. This is because the bit-wise operator inverts each bit in the word. It is not an arithmetic operation, it is a logic operation.
Let's consider the following example that will emphasize this issue for words of length 3:
The range of values that you can represent is from -4 to 3. If you are not familiar with it read about 2's complementnt
011
represent the value 3 -> ~3
is 100
which is -4.
Where -3 is 101
and when subtracting 1 you get 100
which is 4.
so when taking the negative value we need to also subtract 1 because the range is -2^(B) - 2^(B) - 1
and we need to compensate.
Upvotes: 1