Understanding bitwise operations and their application in Java

点点圈 提交于 2019-11-29 12:07:15

You are accidentally specifying an octal literal when you specify a number with a leading zero.

00000010 => 1*8^1 + 0*8^0 => 8
00000100 => 1*8^2 + 0*8^1 + 0*8^0 => 64

The JLS, Section 3.10.1, describes octal and binary literals:

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.

A binary numeral consists of the leading ASCII characters 0b or 0B followed by one or more of the ASCII digits 0 or 1 interspersed with underscores, and can represent a positive, zero, or negative integer.

You are bit-shifting your 8 by one to the left, effectively multiplying it by 2 to get 16. In bits:

00000100 => 00001000
(8 => 16)

Binary literals are expressed with leading 0b, e.g.:

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