This week's book giveaway is in the Android forum.We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!See this thread for details.
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of Head First Android this week in the Android forum!

# 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
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

I agree. Here's the link: http://aspose.com/file-tools

subject: Bitwise inversion operator