Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clarification is needed on bitwise not (~) operator

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?

like image 657
James Raitsev Avatar asked Dec 09 '22 14:12

James Raitsev


2 Answers

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,

0b11110000 = -(~0b1111 + 1) = -(15 + 1) = -16.

This is a natural representation of negative numbers, because

0000001 =  1
0000000 =  0
1111111 = -1  (wrap around)
1111110 = -2
1111101 = -3 etc.

See http://en.wikipedia.org/wiki/Two%27s_complement for detail.


BTW, to print an unsigned value, use the %hhu or %hhx format. See http://www.ideone.com/YafE3.

like image 70
kennytm Avatar answered Dec 29 '22 02:12

kennytm


%d stands for signed decimal number, not unsigned. So your bit pattern, even though it is stored in an unsigned variable, is interpreted as a signed number.

See this Wikipedia entry on signed number representations for an understanding of the bit values. In particular see Two's complement.

like image 40
Brian R. Bondy Avatar answered Dec 29 '22 02:12

Brian R. Bondy