Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Ron McLeod
• Paul Clapham
• Bear Bibeault
• Junilu Lacar
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Henry Wong
Saloon Keepers:
• Tim Moores
• Stephan van Hulst
• Tim Holloway
• salvin francis
• Frits Walraven
Bartenders:
• Scott Selikoff
• Piet Souris
• Carey Brown

# Bitwise complement operator

Ranch Hand
Posts: 76
Hi,

In K & B book for SCJP 1.4, on page 175, the bitwise complement (~) operator is explained:

After line 2 the value of x is -6.

In bit representation 5 is:
0000 0000 0000 0000 0000 0000 0000 0101

the flip-the-bits operator converts it to:
1111 1111 1111 1111 1111 1111 1111 1010

How do I convert the converted bit value back to -6?

Ranch Hand
Posts: 2410
~x = -x - 1

d jones
Ranch Hand
Posts: 76
Thanks Keith,

Is that a rule which I can apply unconditionally all of the time?

Keith Lynn
Ranch Hand
Posts: 2410
Yes, in all cases ~x = -x - 1.

Greenhorn
Posts: 8
int x = 5
bit pattern is 00000000 00000000 00000000 00000101
~x pattern is 11111111 11111111 11111111 11111010

Now since the MSB(most significant bit) is 1 we know its a -ve number. To get the actual value of the -ve number take 2's complement of the number

00000000 00000000 00000000 00000101
+ 1
-----------------------------------
00000000 00000000 00000000 00000110
which is nothing but 6
so ~x = -6

Regards,
Chaitra

author
Posts: 9000
19
and of course this is only a 1.4 topic, not 5.0