java: convert binary string to int

后端 未结 3 656
我在风中等你
我在风中等你 2020-12-20 16:12

I\'m trying to convert a couple of binary strings back to int. However it doesn\'t convert all my binary strings, leaving me a java.lang.NumberFormatException

3条回答
  •  爱一瞬间的悲伤
    2020-12-20 16:46

    From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#toBinaryString(int) : the toBinaryString() method converts its input into the binary representation of the "unsigned integer value is the argument plus 232 if the argument is negative".

    From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html#parseInt(java.lang.String,%20int) : the parseInt() method throws NumberFormatException if "The value represented by the string is not a value of type int".

    Note that both ~0 and ~1 are negative (-1 and -2 respectively), so will be converted to the binary representations of 232-1 and 232-2 respectively, neither of which can be represented in a value of type int, so causing the NumberFormatException that you are seeing.

提交回复
热议问题