This week's book giveaway is in the Performance forum.
We're giving away four copies of The Java Performance Companion and have Charlie Hunt, Monica Beckwith, Poonam Parhar, & Bengt Rutisson on-line!
See this thread for details.
Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Bitwise inversion operator

 
M Bhalli
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
~(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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reverse, x = ~(-x - 1), is also useful.
 
M Bhalli
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you cathy and Eric!!
Actually i couldn't understand the 1's complement process, Now i got it, Thanks a lot
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic