aspose file tools*
The moose likes Beginning Java and the fly likes ~operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "~operator " Watch "~operator " New topic
Author

~operator

Steven Zeng
Ranch Hand

Joined: Jan 15, 2002
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?


SCJP2
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Errr, that is -2 in binary.


"I'm not back." - Bill Harding, Twister
Steven Zeng
Ranch Hand

Joined: Jan 15, 2002
Posts: 41
Jim,why not show me in detail? Thanks a lot.
David O'Meara
Rancher

Joined: Mar 06, 2001
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

Joined: Mar 06, 2001
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

Joined: Mar 06, 2001
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: ~operator