Win a copy of Micro Frontends in Action this week in the Server-Side JavaScript and NodeJS 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
• Liutauras Vilda
• Paul Clapham
• Bear Bibeault
• Jeanne Boyarsky
Sheriffs:
• Ron McLeod
• Tim Cooke
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Jj Roberts
• Stephan van Hulst
• Carey Brown
Bartenders:
• salvin francis
• Scott Selikoff
• fred rosenberger

# bitwise complement operator

Ranch Hand
Posts: 126
hi,
K&B page 175

i didnt understand this:

int x = 5;
and then using complement operator (~x) makes it -6,

actually 5 means :

0000 0000 0000 0000 0000 0000 0000 0101

(~5) :
1111 1111 1111 1111 1111 1111 1111 1010
this should be -2 ,

how the ans is -6?

Ranch Hand
Posts: 2023
1111 1111 1111 1111 1111 1111 1111 1110 is -2

Ranch Hand
Posts: 32
(~5) :
1111 1111 1111 1111 1111 1111 1111 1010
this should be -2 ,

i also dont understand this....same is given in the book...pls explain.

Ranch Hand
Posts: 54
1111 1111 1111 1111 1111 1111 1111 1010

This is a two's compliment representation.Any negative number is reprensted in two's compliment form. Follow a two step method to convert into a decimal number.

1. Flip all the digits

negative of the resulting number is the answer.

so for 1111 1111 1111 1111 1111 1111 1111 1010

1. 0000 0000 0000 0000 0000 0000 0000 0101
2. +1

= 0000 0000 0000 0000 0000 0000 0000 0110
= 6.

ans: = -6.

Another example of representing -2:

procedure is the same as above two steps. flip the digits for 2 add 1.

0000 0000 0000 0000 0000 0000 0000 0010
1. 1111 1111 1111 1111 1111 1111 1111 1101
2 +1
Result: 1111 1111 1111 1111 1111 1111 1111 1110

Hope this example is clear enough.
To summarize bit compliment is different from a two's compliment.
so ~ does flip the digits, but to get the actual number one need to follow two step method.
[ June 02, 2006: Message edited by: pramila ch ]

 Consider Paul's rocket mass heater.