Suppose you have the following C code.
unsigned char a = 1;
printf("%d\n", ~a); // prints -2
printf("%d\n", a); // prints 1
I am surprised to see -2 printed as a result of ~1 conversion:
The opposite of 0000 0001 is 1111 1110. That is anything but -2.
What am I missing here?
It is two’s complement.
In two’s complement representation, if a number x’s most significant bit is 1, then the actual value would be −(~x + 1).
For instance,
This is a natural representation of negative numbers, because
See http://en.wikipedia.org/wiki/Two%27s_complement for detail.
BTW, to print an unsigned value, use the
%hhuor%hhxformat. See http://www.ideone.com/YafE3.