Why “010” equals 8?

流过昼夜 提交于 2019-12-01 16:01:57

问题


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?


回答1:


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 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

Now you should understand why 010 is 8.




回答2:


A leading 0 denotes an octal numeric value so the value 010 can be decoded thus: 010 = 1 * 81 + 0 * 80 = 8




回答3:


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.




回答4:


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 :

1*8^1 + 0*8^0 = 8(decimal) = 1000(binary-only last 4 digits)

Now coming back to the SOP :

System.out.println(010|4);

Applying Bitwise OR on 010 and 4(considering only the last 4 digits) =>

1000|0100

= 1100

= 1*2^3 + 1*2^2 + 0*2^1 + 0*2^0

= 8 + 4 + 0 + 0

= 12(decimal)



来源:https://stackoverflow.com/questions/17469871/why-010-equals-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!