Granny's Programming Pearls "inside of every large program is a small program struggling to get out" JavaRanch.com/granny.jsp
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!

Inversion operator ~

suresh kamsa
Ranch Hand

Joined: Jul 30, 2001
Posts: 149
I know inversion operator will convert all 1 bits to 0 and vice versa.
int x = 6 ;
x = ~x;
How is this valid statement?Could anyone explain for me.
Thanks.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056
You just correctly told us what it does. Why would it be invalid?

Ron Newman - SCJP 1.2 (100%, 7 August 2002)
Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
Hi, Suresh
int x = 6
x = ~x;
6(10) = 00000...0110(2) - 32 bits
~6(10) = 11111...1001(2) = -7(10)
x = ~6 = -7
Best Regards,
Jamal Hasanov
www.j-think.com
Paul Villangca
Ranch Hand

Joined: Jun 04, 2002
Posts: 133
Hi suresh,
You're probably thinking of the statement as an equality statement. It's actually an assignment statement, in which the inverse of x is assigned to x.
x == ~x
then it would always be false (except when x = 0?)
Hope this helps,
Paul Villangca
suresh kamsa
Ranch Hand

Joined: Jul 30, 2001
Posts: 149
Hi Jamal
1. 6(10) = 00000...0110(2) - 32 bits
2. ~6(10) = 11111...1001(2) = -7(10)
3. x = ~6 = -7
In line 2 what is -7(10) and how x = ~6 is valid again. Please explain. Sorry for not getting this bit manipulation into my mind very well.
Ron Newman
Ranch Hand

Joined: Jun 06, 2002
Posts: 1056

x == ~x
then it would always be false (except when x = 0?)

x==~x can never be true for any value of x.
In particular, ~0 == -1.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
Well... dunno:
-x is ~x+1
so ~x is -(1+x);
so x = ~x, can be written x = -(1+x).
Therefore 2x = -1, giving x = -0.5
-Barry B.Sc Maths(Hons) [always wanted to write that ]
[ August 14, 2002: Message edited by: Barry Gaunt ]

Getting someone to think and try something out is much more useful than just telling them the answer.
Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729
By the way, Suresh. Are you back yet? I don't mean here, I mean over there.
My there's bits of you everywhere!
Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
Rule for inversion:
~x = (-x)-1. Sample: ~123= -124; ~(-123) = 122
Best Regards,
Jamal Hasanov
www.j-think.com

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

subject: Inversion operator ~