# ~0 returns -1

Marilyn de Queiroz

Sheriff

Posts: 9066

12

posted 14 years ago

'~' reverses all the bits, so

0000 0000 0000 0000 // decimal zero

becomes

1111 1111 1111 1111 // decimal -1

Search on "binary" and "negative" (search is at the bottom of each page).

0000 0000 0000 0000 // decimal zero

becomes

1111 1111 1111 1111 // decimal -1

Search on "binary" and "negative" (search is at the bottom of each page).

JavaBeginnersFaq

"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt

John Dale

Ranch Hand

Posts: 399

posted 14 years ago

Pretending ints are 8-bit binary:

1 is 00000001

~1 is 11111110

2 is 00000010

So if you add ~1 to 2 and ignore the overflow bit, you get 00000000. Since ~1 plus 2 is 0, ~1 must is a good way to represent -2, and is indeed how Java represents -2, except that ints are really 32 bits, not 8 bits.

1 is 00000001

~1 is 11111110

2 is 00000010

So if you add ~1 to 2 and ignore the overflow bit, you get 00000000. Since ~1 plus 2 is 0, ~1 must is a good way to represent -2, and is indeed how Java represents -2, except that ints are really 32 bits, not 8 bits.