What is Bit Masking?

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

I am fairly new to C programming, and I encountered bit masking. Can someone explain to me the general concept and function of bit masking? Examples are much appreciated.

回答1:

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b Value:  01010101b 

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b Value:  01010101b Result: 00000101b 

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {   uint8_t mask = 0x0f;   // 00001111b   uint8_t value = 0x55;  // 01010101b   return mask & value; } 

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304     uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so                                               // no masking is necessary     uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so                                               // we must mask to get 0x02     uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so                                               // we must mask to get 0x03     uint32_t byte4 = value & 0xff;            // here we only mask, no shifting                                               // is necessary     ... } 

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8; 


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