Understanding bitwise operations and their application in Java

一曲冷凌霜 提交于 2019-12-18 07:12:40

问题


I think understand what they fundamentally do - operate on bits (flip, shift, invert, etc...).

My issue is that I don't know when I'd ever need to use them, and I don't think I fully understand bits.

I know that there are 8 bits in a byte and I know that bits are either a 0 or 1. Now here is where I start to get confused... I believe data types define combinations of bits differently. So if I declare an int, 32 bits are set aside for numbers, if I declare a char, 8 bits are set aside and the bits for that data type define a letter.

Running with that idea, I did the following basic operation in java which confuses me:

int num = 00000010;
System.out.println(num);

This prints 8 and if I define num this way:

int num = 00000100;
System.out.println(num);

This prints 64

So to practice with bitwise operations (just for the hell of it) I tried this:

int num = 00000010 << 1;
System.out.println(num);

And it prints 16 where as I thought it would shift the bits by one to the left and print 64.

What is happening here, and when would I ever need to apply this method of manipulating bits?


回答1:


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


来源:https://stackoverflow.com/questions/18518005/understanding-bitwise-operations-and-their-application-in-java

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