This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# ~operator

Steven Zeng
Ranch Hand
Posts: 41
Hi, here is a example of ~ operator:
int i = 1;
System.out.println(~i);
the result is -2 .
But I think the binary transform should be like this :
00000000 00000000 00000000 00000001 i
11111111 11111111 11111111 11111110 ~i
Who can tell me what is the real transform in this example?

Jim Yingst
Wanderer
Sheriff
Posts: 18671
Errr, that is -2 in binary.

Steven Zeng
Ranch Hand
Posts: 41
Jim,why not show me in detail? Thanks a lot.

David O'Meara
Rancher
Posts: 13459
What you are looking for is a thing called "2's Complement" and it follows like this:
If you are going to represent a number using (for example) 8 bits, you can count from
0000 0000 (ie 0) to
1111 1111 ( ie 2^9 - 1 = 511)
This only lets you store positive numbers.
If you 'give up' the first bit and use it as 'sign bit' to represent positive or negative, and store negative numbers as the bitwise-or of the positive number, you can now count from
1000 0000 (-1 * 2^8-1 = -255) to
0111 1111 (1 * 2^8-1 = 255)
This would be fine, but you notice that
1111 1111 = -0
0000 0000 = +0
ie we have 2 representations for '0'
To get around this, we store negative numbers as the bitwise-or of the positive number, then add one to regain that extra 'bit'
Now:
1000 0000 equals -1 * (2^8-1+1) = -256
1111 1111 equals -1 * (0 + 1) = -1
0000 0000 equals 1 * 0 = 0
0111 1111 equals 1 * (2^8-1) = 255
I hope I got it right, its been a while since I had to do this.
Dave

David O'Meara
Rancher
Posts: 13459
oh, and to complete the thought:
11111111 11111111 11111111 11111110
= -1 x ( 0000000 00000000 00000000 00000001 + 1
)
= -1 x ( 1 + 1 )
= -1 x 2
= -2
QED

David O'Meara
Rancher
Posts: 13459
and to provide a useful link (and take 3 posts instead of 1) this PDF http://www.teicontrols.com/notes/DigitalSystemsEngEE316/1sAnd2sComplement.pdf
Tells you why it's called 2's Complements and what "1's Complement" is (hint: in the explaination I gave, its the one with 2 zeroes)
OK, I'm done now