# Bitwise inversion operator

M Bhalli
Greenhorn
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
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
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
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
Posts: 2
The reverse, x = ~(-x - 1), is also useful.

M Bhalli
Greenhorn
Posts: 9
Thank you cathy and Eric!!
Actually i couldn't understand the 1's complement process, Now i got it, Thanks a lot

 With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.