# Bitwise Complement Confusion

Karen Baog

Ranch Hand

Posts: 120

posted 11 years ago

Hi guys,

I'm having incorrect results using Java's ~ operator.

Here's the code I'm using:

If n == -124, the result I get is -125, after the complement.

I was expecting (and should be) positive 131.

124 -> 0111 1100

invert: 1000 0011 (which is 131)

Please help. I don't know what I'm missing here.

I'm having incorrect results using Java's ~ operator.

Here's the code I'm using:

If n == -124, the result I get is -125, after the complement.

I was expecting (and should be) positive 131.

124 -> 0111 1100

invert: 1000 0011 (which is 131)

Please help. I don't know what I'm missing here.

amerzil co-ed student<br />"Praise be the Code"

David Weitzman

Ranch Hand

Posts: 1365

posted 11 years ago

Java stores integers using two's complement.

Also keep in mind that Java int's are 32 bits long, so even if the int were unsigned the value of ~124 would be much closer to 4 billion than 131.

[ July 25, 2005: Message edited by: David Weitzman ]

Also keep in mind that Java int's are 32 bits long, so even if the int were unsigned the value of ~124 would be much closer to 4 billion than 131.

[ July 25, 2005: Message edited by: David Weitzman ]

Periakaruppan Thiagarajan

Ranch Hand

Posts: 65

posted 11 years ago

Hi karen,

This will answer your question "why did you get -125 instead of 131?".

32bit representation of 124 is 0000 0000 0000 0000 0000 0000 0110 1100

(~n) => 1111 1111 1111 1111 1111 1111 1001 0011 -(a)

Since the most significant bit is 1, take 2's complement to find out the number

2's complement of (a)

0000 0000 0000 0000 0000 0000 0110 1100

+ 0000 0000 0000 0000 0000 0000 0000 0001

Which will give you

0000 0000 0000 0000 0000 0000 0110 1101 which is nothing but binary representaion of 125. Since the most significant bit is 1, it must be a negative number. So the answer is -125.

This will answer your question "why did you get -125 instead of 131?".

32bit representation of 124 is 0000 0000 0000 0000 0000 0000 0110 1100

(~n) => 1111 1111 1111 1111 1111 1111 1001 0011 -(a)

Since the most significant bit is 1, take 2's complement to find out the number

2's complement of (a)

0000 0000 0000 0000 0000 0000 0110 1100

+ 0000 0000 0000 0000 0000 0000 0000 0001

Which will give you

0000 0000 0000 0000 0000 0000 0110 1101 which is nothing but binary representaion of 125. Since the most significant bit is 1, it must be a negative number. So the answer is -125.