Step 1: Convert 9 to binary: 1001 Step 2: Since the signed bit is one, the answer should be a negative integer Step 3: Now convert 0's to 1 and one's to 0. That is, 0110 Step 4: The answer: -6. This is wrong. The answer is -10. What am I doing wrong here? Please explain. Thanks

Barry Gaunt

Ranch Hand

Posts: 7729

posted 12 years ago

Now we have a bit pattern that we must convert to decimal. The high bit is 1 so it's negative. So let's take the two's complement and then afterwards call the number negative again.

Thanks Barry for the short cut method. ~x = -(x+1). It works for x <0, x= Integer.MAX_VALUE, Integer.MIN_VALUE.

So, this is all I need to know for ~x. Or do I definitely need to do it the long way - converting to one's compliment and then adding 1 to the result? Let me know so that I can move on. Thanks once again.

Jay Pawar

Ranch Hand

Posts: 411

posted 12 years ago

Sumitabh, For Integer.MIN_VALUE , the formula doesn't hold good. However, for ~Integer.MAX_VALUE will give you Integer.MIN_VALUE as per the formula.