aspose file tools*
The moose likes Beginning Java and the fly likes Bitwise complement operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Bitwise complement operator" Watch "Bitwise complement operator" New topic
Author

Bitwise complement operator

Andrew Parker
Ranch Hand

Joined: Nov 12, 2001
Posts: 178
Hi,
I have an int x = 5;
0000 0000 0000 0000 0000 0000 0000 0101
~x
converts to:
1111 1111 1111 1111 1111 1111 1111 1010
Now, x = -6 WHY???
I know that the 32th digit represents the -ve sign. How to compute the number "6"?
Thanks for help.
Andrew
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4456
    
    6

Check this thread out: http://www.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=33&t=001584


Junilu - [How to Ask Questions] [How to Answer Questions]
Andrew Parker
Ranch Hand

Joined: Nov 12, 2001
Posts: 178
Hi,
I understand it now.
1111 1111 1111 1111 1111 1111 1111 1010
=
- (2^32) + (2^31....3) + (2^1) = - 6
Thanks
Andrew
Junilu Lacar
Bartender

Joined: Feb 26, 2001
Posts: 4456
    
    6


Now you got me worried that you don't understand...
All you need to do is get the two's complement:
1. complement the number
2. add 1
If you start out with a negative number, you will get its positive and vice versa.
The way you showed it would be way too long unless you've memorized all the powers of 2 and can add really fast. I'm not even sure it'll give you the right result for all, if any, numbers.
 
jQuery in Action, 2nd edition
 
subject: Bitwise complement operator