programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

Bitwise inversion operator (~)

Ranch Hand
Posts: 524
Hi all,
I have to small problem which I want clear off. I know for any integer the inversion value is (-X)-1, but need some more clarification on this.
Say if you want to invert 18 first thing is to write it in the binary format that's;
1001 0010
then you change the 0s into 1s, and vice versa.
which produces
0110 1101 but the answer for ~18 is -19, (-18)-1. So could you please explain the situation here, I know I am wrong in the the 2s complement,
Thank you very much.

Ranch Hand
Posts: 815
Well, 2's complement, you recall, is formed by taking the complement and then add one. Therefore, simply inverting and NOT adding one will yeild one less than if you had inverted and then added one. This response assumes you know how 2's complement works... if not, let me know.
[ November 14, 2004: Message edited by: Nick George ]

Sheriff
Posts: 11343
The 32-bit int value of 18 is:
00000000 00000000 00000000 00010010

So ~18 is:
11111111 11111111 11111111 11101101

...which is -19.

(Or am I missing something here?)

Ransika deSilva
Ranch Hand
Posts: 524
OK, thanks a lot, the answers are superb, thank you once again....