arjunkhera
arjunkhera

Reputation: 979

Negative numbers for toBinaryString in Java

The documentation for Integer.toBinaryString states that, it returns a string representation of the integer argument as an unsigned integer. It also goes on to state, that negative numbers are converted to their magnitude in positive form.

Which from what I understand is two's complement of the negative number. However, when I run the following for negative number, I still obtain the string representation of the number in it's signed form, that is it's two's complement.

Am I missing something here?

System.out.println(Integer.toBinaryString(13));  // 1101
System.out.println(Integer.toBinaryString(-13)); // 11111111111111111111111111110011

Upvotes: 2

Views: 623

Answers (1)

sprinter
sprinter

Reputation: 27986

I'm not sure what version of the javadoc you are viewing. From the Java 15 doc:

The unsigned integer value is the argument plus 2^32 if the argument is negative; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s.

That describes exactly the result you got. Unsigned integer value referred to in the doc just means that all values are converted to non-negative values. The value you are converting is -13. The documentation says that for negative numbers, the value is added to 2^32. 2^32 - 13 = 4294967283. In binary that's 11111111111111111111111111110011 so that is the string that is returned.

Upvotes: 7

Related Questions