开发者

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

Is it safe to cast a long to an int in Java?

For some reason, the following code , I get '-1' as anIntVar. And I have checked 'aLongVar' is not an -1.

public static final long CONST = 1000 * 62;

long aLongVar
int anIntVar =  (int)(aLo开发者_Python百科ngVar/ CONST);


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. 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.


If it was safe it wouldn't require an explicit cast.


A long is 64 bits, and an int is 32 bits, so no, it's not safe.


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. 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.

Is it legal? Yes. Is it safe? No, not unless you do range checks, or are confident that you know your inputs well enough.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜