简体   繁体   English

将long转换为int得出0

[英]Converting long to int gives 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));
    }
}

I ran it but longToInt only returned 0. What is going on? 我运行了它,但longToInt只返回了0。这是怎么回事?

Casting a long to an int is done by removing the top 32 bits of the long . 铸造longint通过去除的顶部的32位完成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". 如果long值大于Integer.MAX_VALUE (2147483647)或小于Integer.MIN_VALUE (-2147483648),则最终结果是丢失了大量位,结果是“垃圾”。


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. 修改后的版本应按预期打印1000000。


... is there a way I can store a long number larger than Integer.MAX_VALUE inside an int number? ...有没有一种方法可以在int编号内存储一个大于Integer.MAX_VALUE的长整数?

No. 没有。

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 2 32 , then you could map a long in that range to an int by subtracting A from it. 您可以做一些映射数字的操作,例如,如果您知道数字始终在AB的范围内,并且B - A小于2 32 ,则可以将该范围内的long int映射到一个int从中减去A

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 2 32 . 但是,如果您long存储的数字域的大小大于2 32 ,则在数学上定义此类映射是不可能的 Which it typically is. 通常是哪个。

because, the long you gave doesn't fit into int. 因为,您给出的时间不适合int。 Give a smaller long and try ! 给出较小的长度并尝试! int (32 bits) long (64 bits) int(32位)长(64位)

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

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