Eng.Fouad
Eng.Fouad

Reputation: 117587

Java 7 binary literals clarification

As you know, the binary literal is a new feature that is introduced in Java 7:

int x = 0b1011;
System.out.println(x); // prints 11 as expected

But, when I tried to get the maximum number from the literal binary I got -1!!!

int x = 0b11111111111111111111111111111111;
System.out.println(x); // prints -1 !!!

Further Details:

System.out.println(Integer.MAX_VALUE);
System.out.println(0b1111111111111111111111111111111); // 31 bits

/* Both print 2147483647 */

/************************************************************************************/

System.out.println(Integer.MIN_VALUE);
System.out.println(0b10000000000000000000000000000000); // 32 bits (increment by 1)

/* Both print -2147483648 */

/************************************************************************************/

// And if you keep increasing the binary literal, its actual value
// will be decreased until you reach the maximum binary literal and
// its actual value will be -1.

System.out.println(0b11111111111111111111111111111111); // 32 bits

/* Prints -1 */

As you can see, the actual value of the literal binary (while the increment) jumps over from the maximum value of int to the minimum one and then keep decreasing till it reaches -1 which is the maximum value of the literal binary.

Is this a bug? or does it have something to do with signed/unsigned numbers?

Upvotes: 2

Views: 2185

Answers (5)

rekire
rekire

Reputation: 47945

Indeed this is a signed int so is 0xffff == 0b11111111111111111111111111111111 == -1.

This is not a positive number.

See also Wikipedia Two's complement.

Upvotes: 4

T.J. Crowder
T.J. Crowder

Reputation: 1074286

Java's int uses 2's complement signed integers. This means the leftmost bit indicates a negative number. So

int x = 0b11111111111111111111111111111111;
//        ^--- this bit

indicates the number is negative. The fact that all of the other bits are also 1 means that the number is (decimal) -1. See the link for details.

Upvotes: 2

Dan Hardiker
Dan Hardiker

Reputation: 3053

Java uses 32 bit signed integers, and the max/min & overflow results you are seeing are valid.

For more information see: http://en.wikipedia.org/wiki/Integer_(computer_science)

Upvotes: 2

fge
fge

Reputation: 121710

This is not a bug at all: since int is unsigned, all bits to 1 does mean -1.

The leftmost bit of a signed integer, in two's complement, is the sign bit. What you see is therefore expected.

Upvotes: 5

user155407
user155407

Reputation:

You're using a signed integer. Bit 32 (the "first" one from the left) is the sign bit. It being 1 means it is a negative number, and 0 means positive. Two's complement is then performed to give the value of -1. Read about that here:

http://tfinley.net/notes/cps104/twoscomp.html

Upvotes: 19

Related Questions