views:

107

answers:

2

If I print out ~100 in Java, I get -101. I'm trying to work this out by hand.

The NOT (~) operator inverts all bits.

100 in binary is 00000000000000000000000001100100.

inverting its bits gives:

11111111111111111111111110011011

Now what? How do I get -101?

+10  A: 

Java uses two's complement (see §4.2 Primitive Types and Values) To negate, you take the complement and add one.

-x = ~x + 1
~x = -x - 1
~100 = -100 - 1

Another way to think about it is to note:

11111111111111111111111111111111 = -1

then do:

  11111111111111111111111111111111 (-1)
- 11111111111111111111111110011011 (~x)
=                          1100100 (100)

-1 - ~x = 100
-1 - 100 = ~x
~x = -101
Matthew Flaschen
http://en.wikipedia.org/wiki/Two%27s_complement
Sam Dufel
A: 

Most systems today work with the 2's complement system. In this system positive numbers are same as in the old binary system, while negative numbers are different (this help map another negative number using the same amount of bits)

If you want to take a number in this system and translate it back to old fashion binary:

~(NegNumber)+1

Neowizard