开发者

Bitwise operators - when/how do you use the operators &, |, ^, >> etc?

I know what they do, I just don't understand when you'd get a use for th开发者_如何学Cem..


When you need to manipulate individual bits of a chunk of data (like a byte or an int). This happens frequently, for example, in algorithms dealing with:

  • encryption
  • compression
  • audio / video processing
  • networking (protocols)
  • persistence (file formats)
  • etc.


I've used them for bit masks before. Say you have an item that has a list of items that can have either a yes or no value (options on a car for instance). You can assign one integer column that will give a value for every option by assigning each option to a binary digit in the number.

Example: 5 = 101 in binary
that would mean:
option 1 - yes
option 2 - no
option 3 - yes

If you were to query on this you would use bitwise & or | operators to select the correct items.

Here is a good article that goes over it in more detail.


One example is if you have an (A)RGB color stored as a 32 bit integer and you want to extract the individual color components:

red = (rgb >> 16) & 0x000000ff;
green = (rgb >> 8) & 0x000000ff;
blue = rgb & 0x000000ff;

Of course as a high level programmer you would normally prefer to use a library function to do this rather than fiddling with bits yourself. But the library might be implemented using bitwise operations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜