Java 为什么我不能为 'long' 赋值 40 亿?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2349488/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why can't I assign a 'long' a value of 4 billion?
提问by Peter
I'm trying to declare a long value in Java, which unfortunately does not work.
我试图在 Java 中声明一个 long 值,不幸的是它不起作用。
This is my code. It results in the following error message: "The literal 4294967296 of type int is out of range".
这是我的代码。它会导致以下错误消息:“int 类型的文字 4294967296 超出范围”。
long bytes = 4294967296;
I need this value to make a file filter that filters out files that are bigger than 4294967296 bytes (4GB). The other way round works without any issues (long size = file.length()
) with every file size, which is why I can't figure out why my declaration is not working.
我需要这个值来制作一个文件过滤器,过滤掉大于 4294967296 字节 (4GB) 的文件。另一种方式long size = file.length()
对每个文件大小都没有任何问题 ( ),这就是为什么我无法弄清楚为什么我的声明不起作用。
回答by Soufiane Hassou
try long bytes = 4294967296L;
to indicate to the compiler that you are using a long
.
尝试long bytes = 4294967296L;
向编译器表明您正在使用long
.
回答by icktoofay
Add L
to the end of the number:
添加L
到数字的末尾:
long bytes = 4294967296L;
回答by Doug Porter
Soufiane is correct. Here is a doc that shows how to declare literals of the various types of numbers in Java:
苏菲安是对的。这是一个文档,展示了如何在 Java 中声明各种类型数字的文字:
回答by polygenelubricants
long
literals are followed by the letter L
or l
(see: JLS 3.10.1). Uppercase is better because it's more legible, lowercase l
looks too similar to 1
.
long
文字后跟字母L
or l
(参见:JLS 3.10.1)。大写更好,因为它更清晰,小写l
看起来与1
.
For your particular number, it's probably easier to write:
对于您的特定号码,编写可能更容易:
long bytes = (1L << 32);
This way, someone who reads the code can quickly tell that bytes
is exactly 2 to the power of 32.
这样,阅读代码的人就可以快速判断出bytes
2 的 32 次方。
回答by Bozho
To answer your question title, the maximum value of a long can be obtained via the constant:
要回答您的问题标题,可以通过常量获得 long 的最大值:
Long.MAX_VALUE
To solve your problem - add the l
(L
) literal after the number.
要解决您的问题 -在数字后添加l
( L
) 文字。
回答by user1660016
The answer to your question "why" is because of 4294967296 is not a long. By default java look on any number as on int or double type (depending on if it has or hasn't dot). And only then convert this number to specified type (long in your case). So the error that you see means that your number is bigger then max value fot int. Adding literal attribute at the end let compiller know which type to use (b - bytes, s - short, l - long, f - float)
你的问题“为什么”的答案是因为 4294967296 不长。默认情况下,java 将任何数字视为 int 或 double 类型(取决于它是否有点)。然后才将此数字转换为指定类型(在您的情况下为 long)。因此,您看到的错误意味着您的数字大于 int 的最大值。在最后添加文字属性让编译器知道要使用哪种类型(b - 字节,s - 短,l - 长,f - 浮点)