为什么 Integer.parseInt("11111111111111111111111111111111",2) 抛出
java.lang.NumberFormatException: For input string: "11111111111111111111111111111111"
在 java 整数是 32 位中,我期望一个有效的返回值,这里出了什么问题?
您假设您将原始位传递给该方法,但实际上您传递的是数字的二进制表示。因此,您最多可以指定 31 位和一个符号。这给出了您预期的结果:
Integer.parseInt("-1", 2);
该方法的约定是,您可以指定任何(合理的)基数,例如十六进制基数:
Integer.parseInt("-1", 36);
从这里应该很明显,这是关于从任意数字系统中的表示到 的转换int
,而不是传递 的原始内容int
。
整数太大。最大值为 2 147 483 647
整数是真正的 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>.
*/
java中的整数是有符号整数。因此 - 或 + 信息需要第一位。
正如 Integer.MAX_VALUE 的 java 文档所说:
Integer.MAX_VALUE 一个常量,保存 int 可以具有的最大值,2^31-1。
32 位“1111111111111111111111111111111”将是 4294967296,因此超出整数范围。
int32 的最大值为 2,147,483,647