简体   繁体   English

将 long 转换为 Int 返回“-1”?

[英]Casting a long to an Int returns in '-1'?

Is it safe to cast a long to an int in Java?在 Java 中将 long 转换为 int 是否安全?

For some reason, the following code, I get '-1' as anIntVar.出于某种原因,下面的代码中,我得到'-1' 作为 anIntVar。 And I have checked 'aLongVar' is not an -1.我已经检查过'aLongVar'不是-1。

public static final long CONST = 1000 * 62;

long aLongVar
int anIntVar =  (int)(aLongVar/ CONST);

If it was safe it wouldn't require an explicit cast.如果它是安全的,则不需要显式强制转换。

No, its not safe.不,它不安全。 Don't do it.不要这样做。 Because, A Long / long has 64 bit and can hold much more data than an Integer / int has 32 bit only.因为,A Long / long64 位,并且可以保存比Integer / int只有32 位更多的数据。 Doing the conversion will result in loss of information.进行转换将导致信息丢失。

If at all you wish to do it, do like this如果您想这样做,请这样做

Use the .intValue() to convert the Long value to an int value.使用.intValue()Long值转换为int值。

A long is 64 bits, and an int is 32 bits, so no, it's not safe. long是 64 位, int是 32 位,所以不,它不安全。

Try尝试

int anIntVar = Math.rint(aLongVar);

You can cast a long to an int and get meaningful results if the value in the long will fit in an int.如果 long 中的值适合 int,您可以将 long 转换为 int 并获得有意义的结果。 If not, you will get high bits truncated.如果没有,您将被截断高位。 In your example you don't show what was in the numerator before you did the division, but -1 is certainly not an impossible value given the right inputs.在您的示例中,您没有在进行除法之前显示分子中的内容,但是在正确的输入下,-1 肯定不是不可能的值。

Is it legal?合法吗? Yes.是的。 Is it safe?安全吗? No, not unless you do range checks, or are confident that you know your inputs well enough.不,除非您进行范围检查,或者确信您对输入足够了解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM