Why is "010" equal to 8?

My simple question is: why:

System.out.println(010|4); 

prints "12"? I understand the bitwise OR operator, but why is "010" equal to 8? This is definitely not a compliment for 2 notifications, so how to decode this number?

+4
source share
4 answers

See Java Language Specification, Chapter 3.10.1 Integer Literals

An integer literal can be expressed in decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base 2).

[...]

the octal digit consists of the ASCII digit 0, followed by one or more ASCII digits from 0 to 7 , alternating with underscores, and may be a positive, zero or negative integer.

You should now understand why 010 is 8 .

+5
source

The leading 0 denotes an octal numerical value , so the value 010 can be decoded in this way: 010 = 1 * 8 1 + 0 * 8 0 = 8

+7
source

This is because java accepts it as an octal literal and therefore produces 12. Try System.out.println(10|4) and the result is 14. Because this time it is accepted as a decimal literal.

+1
source

As mentioned above, 010 is a Octal integer literal . A leading 0 indicates that it is an octal representation. Actual value will be:

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

Now back to SOP:

 System.out.println(010|4); 

Using bitwise OR on 010 and 4 (taking into account 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)

+1
source

Source: https://habr.com/ru/post/1489697/


All Articles