Moon_Watcher
Moon_Watcher

Reputation: 468

Why does ~0 return -1?

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.

Upvotes: 0

Views: 172

Answers (3)

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?

Upvotes: 2

Lev Kuznetsov
Lev Kuznetsov

Reputation: 3728

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

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201517

Because -1 is represented as all ones.

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

Output is

11111111111111111111111111111111

Upvotes: 3

Related Questions