Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why "010" equals 8?

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?

like image 334
Java Adept Avatar asked Jul 04 '13 12:07

Java Adept


People also ask

What is the literal of 010?

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 !

What is the output of INT 010?

When you convert 010 from octal to decimal the result is 8. Any integer preceded by 0 means it is an octal representation.

What is octal in Java?

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.

Which of the following is not a valid numeric literal in Java?

8 is not an octal digit, no more than 2 is valid in binary or G is valid in hexadecimal.


4 Answers

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

like image 72
Reimeus Avatar answered Oct 23 '22 23:10

Reimeus


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.

like image 27
jlordo Avatar answered Oct 23 '22 23:10

jlordo


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.

like image 20
voidMainReturn Avatar answered Oct 23 '22 22:10

voidMainReturn


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)

like image 2
AllTooSir Avatar answered Oct 23 '22 23:10

AllTooSir