带有负数的数字类型解析函数异常
numeric type parse functions exception with negative numbers
System.out.println(Integer.parseInt("7FFFFFFF", 16)); //this is ok.
System.out.println(Integer.parseInt("FFFFFFFF", 16)); //this throws Exception
System.out.println(Integer.valueOf("FFFFFFFF", 16)); //this throws Exception
当我尝试使用 parseInt 或 valueOf 方法将十六进制数转换为整数类型、负数时,该方法为负数抛出 NumberFormatException。我无法在任何地方找到答案。
Integer.parseInt("FFFFFFFF", 16)
并不意味着 "give me the int
with this hexadecimal bit pattern"。意思是"interpret FFFFFFFF
as a base-16 representation of a number, and give me an int
representing the same number".
那个数字是 正 数字 4294967295,它超出了 int
的范围,因此例外。
Integer.parseInt()
和 Integer.valueOf()
期望负值有负号 (-
)。
因此"FFFFFFFF"被解析为正值,比Integer.MAX_VALUE
大。因此例外。
如果要将其解析为负值,请将其解析为 long
并转换为 int
:
System.out.println((int)Long.parseLong("FFFFFFFF", 16));
打印
-1
System.out.println(Integer.parseInt("7FFFFFFF", 16)); //this is ok.
System.out.println(Integer.parseInt("FFFFFFFF", 16)); //this throws Exception
System.out.println(Integer.valueOf("FFFFFFFF", 16)); //this throws Exception
当我尝试使用 parseInt 或 valueOf 方法将十六进制数转换为整数类型、负数时,该方法为负数抛出 NumberFormatException。我无法在任何地方找到答案。
Integer.parseInt("FFFFFFFF", 16)
并不意味着 "give me the int
with this hexadecimal bit pattern"。意思是"interpret FFFFFFFF
as a base-16 representation of a number, and give me an int
representing the same number".
那个数字是 正 数字 4294967295,它超出了 int
的范围,因此例外。
Integer.parseInt()
和 Integer.valueOf()
期望负值有负号 (-
)。
因此"FFFFFFFF"被解析为正值,比Integer.MAX_VALUE
大。因此例外。
如果要将其解析为负值,请将其解析为 long
并转换为 int
:
System.out.println((int)Long.parseLong("FFFFFFFF", 16));
打印
-1