为什么Integer.parseInt(“11111111111111111111111111111111”,2)抛出
java.lang.NumberFormatException: For input string: "11111111111111111111111111111111"
在java中,整数是32位,我希望有一个有效的返回值,这里出了什么问题?
答案 0 :(得分:11)
您假设您将原始位传递给方法,但实际上您传递的是数字的二进制表示。因此,您最多可以指定31位和符号。这给出了您期望的结果:
Integer.parseInt("-1", 2);
方法的合同是这样的,你可以指定任何(合理的)基数,例如 hexatridecimal 基数:
Integer.parseInt("-1", 36);
从这一点来看,显然这是关于从任意数字系统中的表示转换为int
,而不是传递int
的原始内容。
答案 1 :(得分:3)
整数太大了。最大值为2 147 483 647
答案 2 :(得分:3)
整数是真正的32位,但有一位用于正/负号。
此代码
// 31 instead of 32
System.out.println(Integer.parseInt("1111111111111111111111111111111",2));
System.out.println(Integer.MAX_VALUE);
将产生完全相同的数字2147483647。
编辑:
Integer.parseInt规范指出指定负值的正确方法是使用-
减号:
/**
* Parses the string argument as a signed integer in the radix
* specified by the second argument. The characters in the string
* must all be digits of the specified radix (as determined by
* whether {@link java.lang.Character#digit(char, int)} returns a
* nonnegative value), except that the first character may be an
* ASCII minus sign <code>'-'</code> (<code>'\u002D'</code>) to
* indicate a negative value. The resulting integer value is returned.
* <p>
* An exception of type <code>NumberFormatException</code> is
* thrown if any of the following situations occurs:
* <ul>
* <li>The first argument is <code>null</code> or is a string of
* length zero.
* <li>The radix is either smaller than
* {@link java.lang.Character#MIN_RADIX} or
* larger than {@link java.lang.Character#MAX_RADIX}.
* <li>Any character of the string is not a digit of the specified
* radix, except that the first character may be a minus sign
* <code>'-'</code> (<code>'\u002D'</code>) provided that the
* string is longer than length 1.
* <li>The value represented by the string is not a value of type
* <code>int</code>.
* </ul><p>
* Examples:
* <blockquote><pre>
* parseInt("0", 10) returns 0
* parseInt("473", 10) returns 473
* parseInt("-0", 10) returns 0
* parseInt("-FF", 16) returns -255
* parseInt("1100110", 2) returns 102
* parseInt("2147483647", 10) returns 2147483647
* parseInt("-2147483648", 10) returns -2147483648
* parseInt("2147483648", 10) throws a NumberFormatException
* parseInt("99", 8) throws a NumberFormatException
* parseInt("Kona", 10) throws a NumberFormatException
* parseInt("Kona", 27) returns 411787
* </pre></blockquote>
*
* @param s the <code>String</code> containing the integer
* representation to be parsed
* @param radix the radix to be used while parsing <code>s</code>.
* @return the integer represented by the string argument in the
* specified radix.
* @exception NumberFormatException if the <code>String</code>
* does not contain a parsable <code>int</code>.
*/
答案 3 :(得分:1)
java中的整数是有符号整数。因此, - 或+信息需要第一位。
正如Integer.MAX_VALUE的java文档所说:
Integer.MAX_VALUE的 保持int的最大值的常量可以是2 ^ 31-1。
32位“11111111111111111111111111111111”将为4294967296,因此超出整数范围。
答案 4 :(得分:0)
int32的最大值是2,147,483,647