# Confusing with bitwise NOT operator

• 10-16-2009, 07:23 PM
Willi
Confusing with bitwise NOT operator
Hi!

I don't know whether anyone pay attention with bitwise logical NOT operator, but I am confusing with this.

For example, I want to use NOT operator with an integer variable which has value 1, this means (let me take 8 bits instead of 4 bytes) :
Code:

`1 is 0000 0001`
and
Code:

`~1 is 1111 1110`
If we run a program for this problem, we get -2 which is not equal to 1111 1110 at all

The thing that I know is that after 1 is converted to 1's complement, the result is converted back to 2's complement and keep the MSB bit unchanged as the sign bit, that's how we get -2. But why is it like that? Does this have any thing related to performance purpose or it's the rule of representing binary number in form of machine code? :(

Thanks and pardon my ignorance about the very basic thing!
• 10-16-2009, 07:36 PM
r035198x
The advantages of twos complement can found on wikipedia.
• 10-16-2009, 09:03 PM
Willi
so it's all about the sake of performance.

Thanks for the useful topic on Wiki!
• 10-16-2009, 09:06 PM
r035198x
• 10-16-2009, 11:06 PM
CodesAway
Quote:

Originally Posted by Willi
Hi!

I don't know whether anyone pay attention with bitwise logical NOT operator, but I am confusing with this.

For example, I want to use NOT operator with an integer variable which has value 1, this means (let me take 8 bits instead of 4 bytes) :
Code:

`1 is 0000 0001`
and
Code:

`~1 is 1111 1110`
If we run a program for this problem, we get -2 which is not equal to 1111 1110 at all

The thing that I know is that after 1 is converted to 1's complement, the result is converted back to 2's complement and keep the MSB bit unchanged as the sign bit, that's how we get -2. But why is it like that? Does this have any thing related to performance purpose or it's the rule of representing binary number in form of machine code? :(

Thanks and pardon my ignorance about the very basic thing!

It's because the number is a signed number. So the leading 1 says the number is negative.

1111 1111 = -1
1111 1110 = -2
1111 1101 = -3
...

If the number were unsigned (not supported in Java), then 1111 1110 would equal 254.

I've only used the bitwise not operation when working with bitmasks to clear a specific flag. For example "bitmask & ~flag" will clear the specific flag in the bitmask.