Integer.parseInt: 0xff80CBC4 是一个无效的整数
Integer.parseInt: 0xff80CBC4 is an invalid int
有人可以解释为什么以下第二个和第三个语句失败吗?
Integer myColor = 0xff80CBC4 //works
Integer.parseInt("0xff80CBC4".substring(2), 16) //does not work
Integer.decode("0xff80CBC4") //does not work
当运行时,抛出如下异常:
java.lang.NumberFormatException: Invalid int: "ff80CBC4"
如果您在 ff80CBC4
的开头使用 00
而不是 ff
,它会起作用。为什么失败并显示 ff
?
字符串定义的数字对于 Integer 对象来说太大了。例如,您可以使用 Long。
Long a = Long.parseLong("0xff80CBC4".substring(2), 16);
System.out.println(a); //4286630852
Integer max = Integer.MAX_VALUE;
System.out.println(max); //2147483647
请注意,没有 "it does not work" 这样的东西。发出例外情况。 提及他们。
Integer.parseInt()
和 Integer.decode()
失败,因为您尝试解析的文字 0xff80CBC4 对于有符号整数来说太大而无法表示它。 (阅读 two's complement notation 以找出原因。)
事实上,它本可以被解释为一个负整数,但这些函数并不知道这一点,所以他们试图将它解析为一个正整数。
试试这个:
String s = "0xff80CBC4";
int a = Integer.parseInt( s.substring( 2, 4 ), 16 );
int r = Integer.parseInt( s.substring( 4, 6 ), 16 );
int g = Integer.parseInt( s.substring( 6, 8 ), 16 );
int b = Integer.parseInt( s.substring( 8, 10 ), 16 );
int argb = a << 24 | r << 16 | g << 8 | b;
System.out.printf( "%2x %2x %2x %2x %8x\n", a, r, g, b, argb );
它打印:
ff 80 cb c4 ff80cbc4
Integer.decode() 需要正值,但 NumberFormatException 不是由这个原因引发的。
当您将“0xff80CBC4”传递给 Integer.decode() 时,“0x”被丢弃,因此该值为 ff80CBC4,对于 Integer 来说太大了。
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
但是,如果您将“0xff80CBC4”传递给 Long.decode() - 一切都会好的。
有人可以解释为什么以下第二个和第三个语句失败吗?
Integer myColor = 0xff80CBC4 //works
Integer.parseInt("0xff80CBC4".substring(2), 16) //does not work
Integer.decode("0xff80CBC4") //does not work
当运行时,抛出如下异常:
java.lang.NumberFormatException: Invalid int: "ff80CBC4"
如果您在 ff80CBC4
的开头使用 00
而不是 ff
,它会起作用。为什么失败并显示 ff
?
字符串定义的数字对于 Integer 对象来说太大了。例如,您可以使用 Long。
Long a = Long.parseLong("0xff80CBC4".substring(2), 16);
System.out.println(a); //4286630852
Integer max = Integer.MAX_VALUE;
System.out.println(max); //2147483647
请注意,没有 "it does not work" 这样的东西。发出例外情况。 提及他们。
Integer.parseInt()
和 Integer.decode()
失败,因为您尝试解析的文字 0xff80CBC4 对于有符号整数来说太大而无法表示它。 (阅读 two's complement notation 以找出原因。)
事实上,它本可以被解释为一个负整数,但这些函数并不知道这一点,所以他们试图将它解析为一个正整数。
试试这个:
String s = "0xff80CBC4";
int a = Integer.parseInt( s.substring( 2, 4 ), 16 );
int r = Integer.parseInt( s.substring( 4, 6 ), 16 );
int g = Integer.parseInt( s.substring( 6, 8 ), 16 );
int b = Integer.parseInt( s.substring( 8, 10 ), 16 );
int argb = a << 24 | r << 16 | g << 8 | b;
System.out.printf( "%2x %2x %2x %2x %8x\n", a, r, g, b, argb );
它打印:
ff 80 cb c4 ff80cbc4
Integer.decode() 需要正值,但 NumberFormatException 不是由这个原因引发的。
当您将“0xff80CBC4”传递给 Integer.decode() 时,“0x”被丢弃,因此该值为 ff80CBC4,对于 Integer 来说太大了。
// Handle radix specifier, if present
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
}
但是,如果您将“0xff80CBC4”传递给 Long.decode() - 一切都会好的。