0

This is the code I've tried:

int num = ~0;
System.out.print(num);

Output: -1

From what I understand, ~ inverts the bits. So, 0000 0000 would become 1111 1111. How is this -1? I realize that this is a very basic question that involves two's complement, but I'm not able to figure it out.

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
Moon_Watcher
  • 416
  • 1
  • 6
  • 19
  • The most significant bit is worth `-2^31`, not `2^31`. The rest is just arithmetic. – Dawood ibn Kareem Jan 14 '15 at 04:04
  • 4
    Is this question really "what does the ~ operator do," or "why is -1 represented as all 1 bits"? You seem pretty clear on the fact that ~ inverts each bit. This happens completely independently of anything involving two's complement. The fact that all 1-bits represents the integer -1 _is_ two's complement, but that's not what the subject of your question is asking about. – yshavit Jan 14 '15 at 04:12
  • Because if you add 1 to it, it carries all the way through and you get 0. So `num + 1 = 0`? `num` had better be -1. – harold Jan 14 '15 at 07:00

3 Answers3

3

Because -1 is represented as all ones.

System.out.println(Integer.toBinaryString(-1));

Output is

11111111111111111111111111111111
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
2

numbers are reprezented in 32 bit format.

To understand why it shows up as all 1 and then get converted to -1.

Reason:

~0 = ~(00000000 00000000 00000000 00000000) = (11111111 11111111 11111111 11111111) = -1

To understand more, please read this thread: How does the bitwise complement (~) operator work?

Community
  • 1
  • 1
1

1111 1111 is in fact -1 and 1111 1110 is -2. Such is life, not sure how else to put it

Lev Kuznetsov
  • 3,520
  • 5
  • 20
  • 33