0

Here goes a small example.

    int a = 11; //1 0 1 1 is bit representation
    System.out.println(~a);

    Output: -12

As I understand the '~' operator inverts the bits - i.e 1 0 1 1 should now be 0 1 0 0 hence the output should have been 4. What am I missing?

shmosel
  • 49,289
  • 6
  • 73
  • 138
bozo user
  • 241
  • 1
  • 6
  • 15

2 Answers2

5

11 is not represented as 1011, it is represented as: -

0000 0000 0000 0000 0000 0000 0000 1011

It's just that you don't notice see the leading 0's. Remember, ints are of 32 bits.

Now , ~11 would be: -

1111 1111 1111 1111 1111 1111 1111 0100

So, this is a negative number. So, taking it's 2's complement and you get: -

0000 0000 0000 0000 0000 0000 0000 1011 // 1's complement
0000 0000 0000 0000 0000 0000 0000 1100 // 2's complement == -12

Hence, you get -12.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
0

An int is many more digits than 4, it's actually got a bunch of 0's before what you put.

Negative numbers on computers are usually represented as starting with ones. a -1 is generally all ones, -2 is ..11111111111111110, -3 is ..1111111111111101, etc.\

So what you got was a negative number because you changed all those zeros to ones.

If you want to see your number, use ~a & 0xf

0xf will give you a "mask" of ...000001111

Anything anded with that will only retain the last 4 bits, all the rest will be zeroed out.

GREAT question, glad to see people still experiment with / think of this stuff.

Bill K
  • 62,186
  • 18
  • 105
  • 157