# Thread: Confusing with bitwise NOT operator

1. ## 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) :
Java Code:
`1 is 0000 0001`
and
Java 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! 2. Senior Member Join Date
Aug 2009
Posts
2,388
Rep Power
13

## The advantages of twos complement can found on wikipedia. 3. ## so it's all about the sake of performance.

Thanks for the useful topic on Wiki!
Last edited by Willi; 10-16-2009 at 10:06 PM. 4. Senior Member Join Date
Aug 2009
Posts
2,388
Rep Power
13

##  5. ##  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) :
Java Code:
`1 is 0000 0001`
and
Java 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. #### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•