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?
This is by design;
Integer.toBinaryString(emphasis added).
I.e.,
toBinaryStringprovides a way to format an integer as the common two’s complement representation, which is the way most processors actually store signed integers internally.