如何在注意下溢和溢出 int 的同时将 Java 中的 String 转换为 int?
How to convert String to int in Java while taking care underflow and overflow int?
我正在使用以下代码将 String 转换为 int:
int foo = Integer.parseInt("1234");</pre>
如何确保 int 值不上溢或下溢?
As the documentation says, if the input string does not contain a parseable integer, a NumberFormatException
会被抛出。这包括整数但超出 int
.
范围的输入
术语 "underflow" 和 "overflow" 并不是您要在此处查找的术语:它们指的是您在有效范围内有几个整数的情况(例如,2 billion) 并将它们加在一起(或执行一些达到类似效果的算术运算)并得到有效范围之外的整数。这通常会导致诸如由于 Two's Complement 等原因而被卷入底片之类的问题。另一方面,您的问题只是字符串编码整数超出有效范围的简单情况。
您可以随时查看:
long pre_foo = Long.parseLong("1234");
if (pre_foo < Integer.MIN_VALUE || pre_foo > Integer.MAX_VALUE){
//Handle this situation, maybe keep it a long,
//or use modula to fit it in an integer format
}
else {
int foo = (int) pre_foo;
}
我正在使用以下代码将 String 转换为 int:
int foo = Integer.parseInt("1234");</pre>
如何确保 int 值不上溢或下溢?
As the documentation says, if the input string does not contain a parseable integer, a NumberFormatException
会被抛出。这包括整数但超出 int
.
术语 "underflow" 和 "overflow" 并不是您要在此处查找的术语:它们指的是您在有效范围内有几个整数的情况(例如,2 billion) 并将它们加在一起(或执行一些达到类似效果的算术运算)并得到有效范围之外的整数。这通常会导致诸如由于 Two's Complement 等原因而被卷入底片之类的问题。另一方面,您的问题只是字符串编码整数超出有效范围的简单情况。
您可以随时查看:
long pre_foo = Long.parseLong("1234");
if (pre_foo < Integer.MIN_VALUE || pre_foo > Integer.MAX_VALUE){
//Handle this situation, maybe keep it a long,
//or use modula to fit it in an integer format
}
else {
int foo = (int) pre_foo;
}