为什么我不能分配一个“long”价值40亿?
我试图在 Java 中声明一个 long 值,不幸的是这不起作用。
这是我的代码。它会导致以下错误消息:“int 类型的文字 4294967296 超出范围”。
long bytes = 4294967296;
我需要这个值来创建一个文件过滤器,过滤掉大于 4294967296 字节 (4GB) 的文件。相反,对于每个文件大小都没有任何问题(long size = file.length()
),这就是为什么我无法弄清楚为什么我的声明不起作用。
I'm trying to declare a long value in Java, which unfortunately does not work.
This is my code. It results in the following error message: "The literal 4294967296 of type int is out of range".
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试使用
long bytes = 4294967296L;
向编译器表明您正在使用long
。try
long bytes = 4294967296L;
to indicate to the compiler that you are using along
.你的问题“为什么”的答案是因为 4294967296 并不长。默认情况下,java 将任何数字视为 int 或 double 类型(取决于它是否有点)。然后才将此数字转换为指定类型(在您的情况下为 long )。因此,您看到的错误意味着您的数字大于 int 的最大值。在末尾添加文字属性让编译器知道要使用哪种类型(b - 字节、s - 短、l - 长、f - 浮点数)
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)
苏菲安是正确的。以下文档展示了如何在 Java 中声明各种类型数字的文字:
http ://www.janeg.ca/scjp/lang/literals.html
Soufiane is correct. Here is a doc that shows how to declare literals of the various types of numbers in Java:
http://www.janeg.ca/scjp/lang/literals.html
将
L
添加到数字末尾:Add
L
to the end of the number:要回答您的问题标题,可以通过常量获得 long 的最大值:
要解决您的问题 - 在数字后面添加
l
(L
) 文字。To answer your question title, the maximum value of a long can be obtained via the constant:
To solve your problem - add the
l
(L
) literal after the number.long
文字后跟字母L
或l
(请参阅:JLS 3.10.1)。大写更好,因为它更易读,小写l
看起来与1
太相似。对于您的特定数字,它可能更容易编写:
这样,阅读代码的人可以快速知道
bytes
恰好是 2 的 32 次方。long
literals are followed by the letterL
orl
(see: JLS 3.10.1). Uppercase is better because it's more legible, lowercasel
looks too similar to1
.For your particular number, it's probably easier to write:
This way, someone who reads the code can quickly tell that
bytes
is exactly 2 to the power of 32.