Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Inversion operator ~

suresh kamsa
Ranch Hand
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
Posts: 1056
You just correctly told us what it does. Why would it be invalid?

Jamal Hasanov
Ranch Hand
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
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
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
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
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 ]

Barry Gaunt
Ranch Hand
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
Posts: 411
Rule for inversion:
~x = (-x)-1. Sample: ~123= -124; ~(-123) = 122
Best Regards,
Jamal Hasanov
www.j-think.com