Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

~0 returns -1

 
Urooj Ajmal
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why and how does ~0 return -1 and ~1 return -2.
 
Marilyn de Queiroz
Sheriff
Posts: 9065
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
'~' 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).
 
John Dale
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic