Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

bitwise inversion ~ operator

 
anand nagpal
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
class test{
public static void main(String args[]){
int i = 1;
System.out.println(~i);
}
}
Output : -2
can someone kindly explain me what exactly ~ operator does ?
thanks
anand


 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
~ just inverts all bits of the number
In this case
i=1 => 00000000 00000000 00000000 00000001
~i => 11111111 11111111 11111111 11111110
And in binary ~1 equals -2.
If you do Integer.parseInt("11111111111111111111111111111110",2);
you'll get -2
More on binary:
2 in binary is 00000000 00000000 00000000 00000010
if you want to get the negative value of 2 you have to take the 2's complement of 2 which is just inverting all bits and adding 1.
So if you invert it you get 11111111 11111111 11111111 11111101
and then you add one and you get
11111111 11111111 11111111 11111110 which is the same pattern as above and thus ~1 = -2
The genral rule is that ~i = -i-1
HIH
------------------
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform
 
R K Singh
Ranch Hand
Posts: 5382
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Valentin Crettaz:

And in binary ~1 equals -2.

Hi Valentin
But I think
~1 in NOT equal to -2 in BINARY.
It is the implementation of negative number which makes ~1 equal to -2, as neagtive numbers are stored as 2's compliment numbers.
if we have lets say 4 bit integer size then -1 will be stored as :
i) 1 in binary = 0001
ii) 2's compliment of 1 = 1111 (invert 0001, becomes 1110, add 1, becomes 1111);
so -1 will be stored as 1111 (NOTE: MSB is '1'(on) which indicates that number is negative. 2's compliment is of positive number(eg. 1))


This is done for lot of reason, it makes airthmetic operation fasts(there are lot of algos for binary airthmetic), and it also makes -0 and +0 equal.
I just want to say that it is the implementation which makes ~1 to equal to -2, in binary it will be some different number.
CMIW
AND thanks a lot for the general rule. It will really help us in binary questions in SCJP.
------------------
Regards
Ravish
[This message has been edited by ravish kumar (edited November 18, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic