The output of this program is -13. I have never fully understood ~ operator in C. Why does it give -13 as output? How to limit ~ operator to just 4 bits of a number?
<
(12)10
in binary is (1100)2
The tilde is the bitwise complement operator which makes 1100
--> 0011
. However if you working on a 32 bit platform actually what we get is:
0000 0000 0000 0000 0000 0000 0000 1100
Whose bitwise complement is:
1111 1111 1111 1111 1111 1111 1111 0011
|
Now since the left most bit is for sign the number becomes negative. If you use unsigned int you will be able to understand better what is happening:
unsigned int a = 12;
a = ~a;
Will give:
1111 1111 1111 1111 1111 1111 1111 0011
Which is 4294967283