Converting 32-bit binary string with Integer.parseInt fails

前端 未结 4 727
慢半拍i
慢半拍i 2020-12-07 01:14

Why does this part of code fail:

Integer.parseInt(\"11000000000000000000000000000000\",2);

Exception in thread \"main\" java.lang.NumberFormatException: For         


        
4条回答
  •  离开以前
    2020-12-07 02:04

    This is because for Integer.parseInt "11000000000000000000000000000000" is not a two's complement representation of -1073741824 but a positive value 3221225472 which does not fit into int values range -2147483648 to 2147483647. But we can parse two's complement binary string representation with BigInteger:

    int i = new BigInteger("11000000000000000000000000000000", 2).intValue()
    

    this gives expected -1073741824 result

提交回复
热议问题