Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ~0 is -1?

So as I was reading about ~,

Performs the NOT operator on each bit.

So I tried:

 0 = 00000000000000000000000000000000

         so ~0 should be

~0 = 11111111111111111111111111111111

But when I tried, it returns -1. Isn't 11111111111111111111111111111111 is 4294967295 in decimal?

like image 625
Derek 朕會功夫 Avatar asked Jun 10 '12 18:06

Derek 朕會功夫


2 Answers

It's interpreted as a signed integer, and in two's complement, an integer with all bits 1 is -1.

like image 196
Daniel Fischer Avatar answered Sep 26 '22 04:09

Daniel Fischer


Only if the type is unsigned. Signed integers use the topmost bit as a negation flag - and thus setting it to 1 results in a negative number. See Two's Complement.

like image 32
Amber Avatar answered Sep 26 '22 04:09

Amber