programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Value of ~10

Greenhorn
Posts: 19
Hi All,

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.

Any body please clarify how it is displaying -11.

Regards,
Swathi.

Ranch Hand
Posts: 7729
Hint: there are 32 bits in an int. You are only considering 4 of them. What about the other 28 bits?

Swathi Sree
Greenhorn
Posts: 19
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
Posts: 7729
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 ]

Ranch Hand
Posts: 531
What you are missing is that Java uses twos complement.

You took the complement of 10 correctly. I will round off to a byte for clarity:

00001010 -> 11110101

To get the value of a negative number you need to take the twos complement: flip and add one and negate. Try it, it's -11!

11110101 -> 00001010 -> 00001011 -> 11 -> -11

author
Sheriff
Posts: 14112
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