aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Bitwise inversion operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Bitwise inversion operator" Watch "Bitwise inversion operator" New topic
Author

Bitwise inversion operator

M Bhalli
Greenhorn

Joined: Oct 09, 2003
Posts: 9
~(bitwise inversion operator) it reverse all the bits of interger variable. What i m thinking that if int x=3;then 3 is being stored in x using 32 bits like 00000000000000000000011 (32bits), and when u apply ~x then 11 should convert to 00 and rest of all zeros should convert into 1's is it right, but when i compile the code the result is quite different. Please tell me what is going on here.
Thank you, M Bhalli
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
class TestInvert {
public static void main (String [] args) {

int a = ~3;
System.out.println(Integer.toBinaryString(a));
}
}
The result is as expected in binary.
--Cathy.
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
class TestInvert {
public static void main (String [] args) {

System.out.println(Integer.toBinaryString(3));
int a = ~3;
System.out.println(Integer.toBinaryString(a));
System.out.println(a); //line 1
}
}
Now see line 1, you get -4 is decimal because,
11111111111111111111111111111100 //binary (2's complement)
to get its decimal take 2's complement
Step 1: Invert bits
000...000 11
Step 2: Add 1
000...00100 // decimal 4
Since signed bit was 1, sso the final result is -4.
Does this help?
--Cathy.
Cathy Song
Ranch Hand

Joined: Aug 24, 2003
Posts: 270
The following formula has helped me a lot:
x : binary integer
~x : bits inversed (1's complement)
-x = ~x + 1
here -x is the negative binary value.
--Cathy.
Eric Y. Wu
Greenhorn

Joined: Oct 11, 2003
Posts: 2
The reverse, x = ~(-x - 1), is also useful.
M Bhalli
Greenhorn

Joined: Oct 09, 2003
Posts: 9
Thank you cathy and Eric!!
Actually i couldn't understand the 1's complement process, Now i got it, Thanks a lot
 
Consider Paul's rocket mass heater.
 
subject: Bitwise inversion operator