将long转换为int得到0 [英] Converting long to int gives 0

查看:496
本文介绍了将long转换为int得到0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在测试这段代码:

I have been testing out with this snippet of code:

public class Test {
    public static int longToInt(long num) {
        return (int) (num);
    }

    public static void main(String[] args) {
        System.out.println(longToInt(100000000L));
    }
}

我跑了但是longToInt只返回0.什么是继续?

I ran it but longToInt only returned 0. What is going on?

推荐答案

long 投射到 int 是通过删除 long 的前32位来完成的。如果 long 值大于 Integer.MAX_VALUE (2147483647)或小于整数。 MIN_VALUE ( - 2147483648),净效果是您丢失了有效位,结果是垃圾。

Casting a long to an int is done by removing the top 32 bits of the long. If the long value is larger than Integer.MAX_VALUE (2147483647) or smaller than Integer.MIN_VALUE (-2147483648), the net effect is that you lose significant bits, and the result is "rubbish".

话虽如此,你提供的代码并不像你说的那样......如果你正确编译并运行它。原始版本应该打印一个意外的数字......但不是零。修改后的版本应按预期打印1000000.

Having said that, the code you supplied does not behave like you say it does ... if you compile and run it correctly. The original version should print an unexpected number ... but not zero. The modified version should print 1000000 as expected.


...有没有办法我可以在int数中存储大于Integer.MAX_VALUE的长数字吗?

... is there a way I can store a long number larger than Integer.MAX_VALUE inside an int number?

否。

严格来说是......在某些情况下。您可以执行某些操作来映射数字,例如,如果您知道您的数字始终在 A B B - A 小于2 32 ,然后你可以映射一个 long 在该范围内通过从中减去 A int

Well strictly yes ... in some circumstances. You could do something to map the numbers, For example, if you know that your numbers are always in the range A to B, and B - A is less than 232, then you could map a long in that range to an int by subtracting A from it.

但是,如果您在<$ c $中存储的数字域的大小,则在数学上不可能来定义此类映射c> long 大于2 32 。它通常是。

However, it is mathematically impossible to define such a mapping if the size of the domain of numbers you are storing in the long is larger than 232. Which it typically is.

这篇关于将long转换为int得到0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆