左侧为 0 的长值
为什么会发生这种行为?
long value = 123450;
System.out.println("value: " + value);
值:
123450
long value = 0123450;
// ^
System.out.println("value: " + value);
值:42792
这42792是什么?
Why this behavior happens?
long value = 123450;
System.out.println("value: " + value);
value: 123450
long value = 0123450;
// ^
System.out.println("value: " + value);
value: 42792
What is this 42792?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
正如以
0x
开头的文字被视为十六进制数字(基数 16)一样,以0
开头的文字也被视为八进制数字,即基数为 8 的数字。(尝试写 0789 ,你会看到编译器会抱怨。)
以8为基数的数字123450代表数字
1×85 + 2×8 4 + 3×83 + 4×82 + 5×81 + 0×80 = 42792
Just as literals starting with
0x
are treated as hexadecimal numbers (base 16), literals starting with a0
are treated as octal numbers, i.e., numbers in base 8.(Try writing 0789, and you'll see that the compiler will complain.)
The number 123450 in base 8 represents the number
1×85 + 2×84 + 3×83 + 4×82 + 5×81 + 0×80 = 42792
如果在数字前加上零,则该数字被理解为八进制(基数为 8)。然而, println 以 10 为基数写入。
八进制 123450 = 十进制 42792。
If you prefix a number with a zero, it is understood to be octal (base 8). However, println writes it in base 10.
123450 octal = 42792 decimal.
这就是 java 表示八进制文字的方式。看看这个:
http://download.oracle.com/javase /tutorial/java/nutsandbolts/datatypes.html
如果您想要打印左侧带有零的内容,则需要使用 DecimalFormat 格式方法。
http://download.oracle.com/javase/6 /docs/api/java/text/DecimalFormat.html
在这种情况下,您可以这样做:
That's the way java represent an octal literal. Take a look at this:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
If what you want is to print something with zeros in the left you need to use DecimalFormat format method.
http://download.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html
In that case you do this:
八进制文字。有关 Java 数字文字的详细描述(尽管有些枯燥),请参阅 Java 语言规范 3.10.1。要查找和研究更多类似的有趣内容,请参阅“Java puzzlers”一书。
Octal literal. See Java Language Specification, 3.10.1 for detailed, albeit somewhat dry, description of Java number literals. To find and study more fun stuff like that, refer to 'Java puzzlers' book.
此功能可以追溯到早期的“C”时代。前导“0”表示八进制,前导“0x”表示十六进制。有人建议 JDK 7 中的二进制数字为“0b”。
您可以使用
Integer.decode(String)
解析这样的数字,它也接受前导“#”作为十六进制数字。This feature dates back to the early 'C' days. A leading '0' is for octal, a leading '0x' is for hexidecimal. It has been proposed that '0b' be for binary numbers for JDK 7.
You can parse such a number with
Integer.decode(String)
which also accepts a leading '#' as a hexi-decimal number.