Why “010” equals 8?

前端 未结 5 481
予麋鹿
予麋鹿 2021-01-18 00:30

My simple question is why:

System.out.println(010|4);

prints \"12\"? I understand bitwise OR operator but why \"010\" equals 8? It\'s defin

5条回答
  •  再見小時候
    2021-01-18 01:16

    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)

提交回复
热议问题