java 为什么“010”等于8?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17469871/
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 "010" equals 8?
提问by Java Adept
My simple question is why:
我的简单问题是为什么:
System.out.println(010|4);
prints "12"? I understand bitwise OR operator but why "010" equals 8? It's definitely not compliment 2's notification, so how to decode this number?
打印“12”?我理解按位或运算符,但为什么“010”等于 8?这绝对不是恭维2的通知,那么如何解码这个数字呢?
回答by Reimeus
A leading 0
denotes an octal numeric valueso the value 010
can be decoded thus: 010 = 1 * 81+ 0 * 80= 8
前导0
表示八进制数值,因此010
可以对值进行解码:010 = 1 * 81+ 0 * 80= 8
回答by jlordo
Have a look at the Java Language Specification, Chapter 3.10.1 Integer Literals
An integer literal may be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).
[...]
An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7interspersed with underscores, and can represent a positive, zero, or negative integer.
整数文字可以用十进制(基数 10)、十六进制(基数 16)、八进制(基数 8)或二进制(基数 2)表示。
[...]
一个八进制数字由一个ASCII数字0,随后的一个或多个的ASCII数字0至7中的用下划线穿插,并可以代表正,零或负的整数。
Now you should understand why 010
is 8
.
现在你应该明白为什么010
是8
.
回答by voidMainReturn
That is because java takes it as an octal literal and hence produces 12. Try System.out.println(10|4)
and the result is 14. Because this time it is taken as decimal literal.
那是因为 java 把它当作八进制文字,因此产生 12。尝试System.out.println(10|4)
,结果是 14。因为这次它被当作十进制文字。
回答by NINCOMPOOP
As everybody mentioned here that 010
is an Octal Integer literal. The leading 0
specifies that it is an octal representation . Actual value will be :
正如这里的每个人都提到的那样,这010
是一个Octal Integer 字面量。前导0
指定它是八进制表示。实际值将是:
1*8^1 + 0*8^0 = 8(decimal) = 1000(binary-only last 4 digits)
1*8^1 + 0*8^0 = 8(十进制)= 1000(只有二进制的最后 4 位数字)
Now coming back to the SOP :
现在回到 SOP:
System.out.println(010|4);
Applying Bitwise OR on 010
and 4
(considering only the last 4 digits) =>
对010
和应用按位或4
(仅考虑最后 4 位数字)=>
1000|0100
= 1100
= 1*2^3 + 1*2^2 + 0*2^1 + 0*2^0
= 8 + 4 + 0 + 0
= 12(decimal)
1000|0100
= 1100
= 1*2^3 + 1*2^2 + 0*2^1 + 0*2^0
= 8 + 4 + 0 + 0
= 12(十进制)
回答by Anuj Arun Kathavale
Any number in Java which fulfill the below Conditions - A. number Should have three or More Digital B.Number should Start with 0. If above Condition are true then number treated as Octal_Base (8) Number. Therefore, 010=(8^2)*0+(8^1)*1+(8^0)*0=64*0+8*1+1*0=8 So, 010=8
Java 中满足以下条件的任何数字 - A. 数字应具有三个或更多数字 B. 数字应以 0 开头。如果上述条件为真,则将数字视为 Octal_Base (8) 数字。因此,010=(8^2)*0+(8^1)*1+(8^0)*0=64*0+8*1+1*0=8 所以,010=8