This week's giveaway is in the Android forum. We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line! See this thread for details.

I am not able to understand how come ~10 is displaying -11? the Binary value of 10 is 1010 and one's complement gives 0101 which is 5. As the sign bits are changed, it should be -5. If I print the binary string, then also it is printing "11111111111111111111111111110101". But if I print toString it is again giving same -11.

Thanks for pointing out that only 4 bits are considered. Even if I consider all bits except the top most bit(sign bit) ita giving 2147483637. resulting in negative sign gives -2147483637.

To get the decimal number of the ones complementation of 10, I used calculator.But in the exam that won't be available(I am preparing for the java certification). Is there any way to calculate this easily?

Thanks & Regards, Swathi.

Barry Gaunt
Ranch Hand

Joined: Aug 03, 2002
Posts: 7729

posted

0

First a bit of maths: By using 2 complement we get -x = ~x + 1. So ~x = -x - 1 = -(x + 1). Using that, ~10 = -(10 + 1) = -11.

Now let's try with bits:

[ August 27, 2005: Message edited by: Barry Gaunt ]

With other words, the sign bit doesn't work the way you think it works. Putting a sign bit in front of a binary 5 doesn't make it a -5.

There are at least two reasons to use the two's complement:

- you don't waste the zero (if it worked like you thought, there also would be a negative zero), and

- addition with negative numbers works *exactly* like with positive numbers. That is, if you have four bit numbers

The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus