Search code examples
javabinaryparseint

Java - Integer.parseInt() not returning a negative number when radix=2


As far as I know, when using 2's complement, and the first number is a 1, then you flip the numbers and find the value of the new byte and make it a negative.The javadoc says that Integer.parseInt(String s, radix) and Integer.valueOf(String s, radix) both should return a signed integer object, but when I test it out with this:

System.out.println(Integer.parseInt("10000001", 2));

System.out.println(Integer.valueOf("10000001", 2));

I get:

129

129

even though my calculations get me -127. Whats interesting is that

System.out.println(Integer.parseInt("-10000001", 2));

prints out:

-129

Anyone know of a different java method that if you input a byte (and radix = 2), then the method will return a correctly signed value?


Solution

  • If it's always going to be a byte, then this should do the trick:

    int i = Integer.parseInt("10000001", 2);
    byte b = (byte) i;
    

    The integer value will be 129, but when you cast it to a byte it will change to -127.