简体   繁体   English

原始int值转换?

[英]Primitive int value conversion?

public class Test3 {

    public static void main(String[] args) {
        int i = 010;
        System.out.println(i); // prints 8          
    }

}

How come it prints 8? 它如何打印8? How is it getting converted? 如何转换? Debugging the program didn't help. 调试程序没有帮助。

010 is parsed as an octal number (as any number literal starting with 0 ). 010被解析为八进制数字(任何以0开头的数字文字)。 Its decimal value is 8. System.out.println prints the decimal value. 其十进制值为System.out.println打印十进制值。

Any number of digits, optionally preceded by a sign (+ or -). 任意数量的数字,可以选择在其后加上一个符号(+或-)。 Decimal digits assumed by default (0-9), but a 0 prefix introduces octal digits (0-7), and > 0x hexadecimal digits (0-f). 默认情况下采用十进制数字(0-9),但前缀0会引入八进制数字(0-7)和> 0x十六进制数字(0-f)。

Since you prefixed 10 with a 0 then it's read as an octal rather than decimal. 由于您在10前面加上0前缀,因此它将被读取为八进制而不是十进制。

Converting octal to decimal in Java: 在Java中将八进制转换为十进制:

String octal = "010";
int decimal = Integer.parseInt(octal, 10);

System.out.println(decimal);

Output: 输出:

10

这是八进制到十进制的转换。有关更多信息,请访问: http : //www.buzzle.com/articles/octal-to-decimal-how-to-convert.html

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

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