my dog learned polymorphism
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "bitwise inversion ~ operator " Watch "bitwise inversion ~ operator " New topic

bitwise inversion ~ operator

anand nagpal

Joined: Nov 15, 2001
Posts: 2
Hi all,
class test{
public static void main(String args[]){
int i = 1;
Output : -2
can someone kindly explain me what exactly ~ operator does ?

Valentin Crettaz
Gold Digger

Joined: Aug 26, 2001
Posts: 7610
~ 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
Valentin Crettaz
Sun Certified Programmer for Java 2 Platform

[Blog] [Blogroll] [My Reviews] My Linked In
R K Singh
Ranch Hand

Joined: Oct 15, 2001
Posts: 5382
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.
AND thanks a lot for the general rule. It will really help us in binary questions in SCJP.
[This message has been edited by ravish kumar (edited November 18, 2001).]

"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
I agree. Here's the link:
subject: bitwise inversion ~ operator
It's not a secret anymore!