将负Integer.MIN转换为正long [英] Converting negative Integer.MIN to positive long
问题描述
我正在尝试使用以下代码将负Integer.MIN转换为正长值:
I am trying to convert negative Integer.MIN to positive long value using below code :
long lv = -1 * value_int;
除了value_int = Integer.MIN_VALUE的值外,上面的代码工作正常。在Integer.MIN_VALUE的情况下,lv的值始终为Integer.MIN_VALUE;
Above code works perfectly except when value of value_int = Integer.MIN_VALUE. In Integer.MIN_VALUE case, value of lv is always Integer.MIN_VALUE;
以下代码工作在所有情况下包括Integer.MIN_VALUE
Below code work in all cases including Integer.MIN_VALUE
long lv = value_int;
lv = -1 * value_int;
任何想法为什么long lv = -1 * value_int在Integer.MIN_VALUE情况下不起作用?
Any idea why long lv = -1 * value_int does not work in Integer.MIN_VALUE case?
推荐答案
1
(前面是一元 -
运算符,在本例中是一个 int
字面值。由于 value_int
也是 int
,因此乘法是以 int $ c完成的$ c> - 哪个溢出,然后才提升为长。如果您使用
long
字面值,则乘法将作为long进行,您将得到正确的结果:
1
(preceded by the unary -
operator, in this case) is an int
literal. Since value_int
is also an int
, the multiplication is done as an int
- which overflows, and only then promoted to a long. If you use a long
literal instead, the multiplication will be done as a long, and you'd get the correct result:
long lv = -1L * value_int;
// Here-----^
这篇关于将负Integer.MIN转换为正long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!