Reputation: 8229
Why are this two methods using two different approaches while processing binary numbers? String which represents negative binary number in Integer.parseInt(String s, 2)
method should start with -
character, but Integer.toBinaryString(int i)
returns string with additional 1 ahead. So, this code
Integer.parseInt(Integer.toBinaryString(-1), 2);
throws java.lang.NumberFormatException
. What is the reason of such behavior?
Upvotes: 2
Views: 1732
Reputation: 917
Integer::parseInt(String,int)
is expecting a string and so it is looking for the -
symbol in negative number. Whereas the Integer::toBinaryString(int)
is for giving you the binary equivalent of your input. In Binary, negative numbers are represented by 2's Compliment.
Upvotes: 0
Reputation: 363817
This is by design; Integer.toBinaryString
Returns a string representation of the integer argument as an unsigned integer in base 2.
(emphasis added).
I.e., toBinaryString
provides a way to format an integer as the common two's complement representation, which is the way most processors actually store signed integers internally.
Upvotes: 2