0

According to my comprehension, Integer type in Java is 32-bit-signed, the most significant bit is the signed bit. This is why Integer.MAX_VALUE is 2147483647, which is:

1111111111111111111111111111111(1 repeated in 31 times).

So I assume that it actually can be represented as:

01111111111111111111111111111111(a 0 followed by 1 repeated 31 times)

The 0 means this is a positive integer.

Then for the following codes:

    int test = -2147483647;
    String converted = Integer.toBinaryString(test);
    System.out.println(converted);

The output is:

 10000000000000000000000000000001

Why the output is like above? For me, the binary stream should be represented as -1, since the most significant bit is 1 means negative.

Like this:

    int minusOne = -1;
    String converted1 = Integer.toBinaryString(test);
    System.out.println(converted1);

The output is the same as above:

10000000000000000000000000000001

Any explanation?

0

2 Answers 2

2

Look at the folowing two snippets, did you find the problem:

int test = -2147483647;
String converted = Integer.toBinaryString(test);
System.out.println(converted);

int minusOne = -1;
String converted1 = Integer.toBinaryString(test);
System.out.println(converted1);

You are printing out the same variable test, that's why the output is the same. If you printout "minusOne" it would be all 1's.

10000000000000000000000000000001 -> -2147483647 = Integer.MIN_VALUE + 1
11111111111111111111111111111111 -> -1

1111111111111111111111111111111  -> Integer.MAX_VALUE = 2147483647
10000000000000000000000000000000 -> Integer.MAX_VALUE + 1
10000000000000000000000000000000 -> Integer.MIN_VALUE = -2147483648
10000000000000000000000000000001 -> Integer.MIN_VALUE + 1
Sign up to request clarification or add additional context in comments.

Comments

1

In addition to @dragon66's point, be aware that these are two's complement numbers. They are not represented as sign, magnitude.

In two's complement representation, one negates a number by inverting all the bits, then adding 1. This way, there's only one representation of 0.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.