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?
I understand bitwise OR operator but why "010" equals 8? It's definitely not compliment 2's notification, so how to decode this number? That is an octal literal ! More specifically : 1*8^1 + 0*8^0 = 8 !
When you convert 010 from octal to decimal the result is 8. Any integer preceded by 0 means it is an octal representation.
Octal is a number system where a number is represented in powers of 8. So all the integers can be represented as an octal number. Also, all the digit in an octal number is between 0 and 7. In java, we can store octal numbers by just adding 0 while initializing. They are called Octal Literals.
8 is not an octal digit, no more than 2 is valid in binary or G is valid in hexadecimal.
A leading 0
denotes an octal numeric value so the value 010
can be decoded thus: 010 = 1 * 81 + 0 * 80 = 8
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
.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With