wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes ~0 returns -1 Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "~0 returns -1" Watch "~0 returns -1" New topic
Author

~0 returns -1

Urooj Ajmal
Greenhorn

Joined: Jul 14, 2002
Posts: 3
why and how does ~0 return -1 and ~1 return -2.
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9047
    
  10
'~' 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).


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

Joined: Feb 22, 2001
Posts: 399
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.
 
 
subject: ~0 returns -1