Integer.parseInt(Integer.toBinaryString(-100), 2)
报异常, java.lang.NumberFormatException: For input string: "11111111111111111111111110011100"。哪位大大可以解释下啊
因为Integer.toBinaryString()是将int转换为无符号表示的二进制数的String,而Integer.parseInt()是将表示有符号数的String转换为int。-100的无符号二进制表示以有符号方式去解释就超出了int的值域,所以这里会抛NumberFormatException。所有负的int替换掉这个例子的-100都会遇到同样的问题。
java中int 类型的范围是:-2147483648 到2147483648
而你提供的数值(用字符串表示的)是:
"11111111111111111111111110011100"
明显,越界了
[code="java"]
Integer.parseInt(Integer.toBinaryString(-100), 2)
// 先变为:
//Integer.parseInt("11111111111111111111111110011100",2)
// 然后解析,就越界了。
// java中int 类型的范围是:-2147483648 到2147483648
// 小于 11111111111111111111111110011100
[/code]
标记一下,关注此问题
请阅读Integer.toBinaryString()的文档:
[quote]Returns a string representation of the integer argument as an unsigned integer in base 2.
[color=red]The unsigned integer value is the argument plus 2^32 if the argument is negative[/url]; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters '0' ('\u0030') and '1' ('\u0031') are used as binary digits.[/quote]
抱歉前一条回复打错tag了……
[quote]Returns a string representation of the integer argument as an unsigned integer in base 2.
[color=red]The unsigned integer value is the argument plus 2^32 if the argument is negative[/color]; otherwise it is equal to the argument. This value is converted to a string of ASCII digits in binary (base 2) with no extra leading 0s. If the unsigned magnitude is zero, it is represented by a single zero character '0' ('\u0030'); otherwise, the first character of the representation of the unsigned magnitude will not be the zero character. The characters '0' ('\u0030') and '1' ('\u0031') are used as binary digits.[/quote]