Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does printf("%d", ~0) output -1? [duplicate]

Why does printf("%d", ~0); yield a value of -1? Shouldn't it be 1 since the ~ operator converts each 1-bit into a 0-bit and vice versa?

From what I understand is 0000 will be negated to 1111.

like image 233
tuyen le Avatar asked Jan 07 '23 13:01

tuyen le


1 Answers

~ is a bitwise complement operator . 00000000 is flipped to 11111111.

If you take 2'scomplement of 1(00000001) what you get is 11111111 which is to represent -1 in binary.

Therefore the output is -1.

like image 77
ameyCU Avatar answered Jan 17 '23 16:01

ameyCU