What is Bit Masking?

414,896

Solution 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;

Solution 2

Masking means to keep/change/remove a desired part of information. Lets see an image-masking operation; like- this masking operation is removing any thing that is not skin-

enter image description here

We are doing AND operation in this example. There are also other masking operators- OR, XOR.


Bit-Masking means imposing mask over bits. Here is a bit-masking with AND-

     1 1 1 0 1 1 0 1   [input]
(&)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     0 0 1 0 1 1 0 0  [output]

So, only the middle 4 bits (as these bits are 1 in this mask) remain.

Lets see this with XOR-

     1 1 1 0 1 1 0 1   [input]
(^)  0 0 1 1 1 1 0 0    [mask]
------------------------------
     1 1 0 1 0 0 0 1  [output]

Now, the middle 4 bits are flipped (1 became 0, 0 became 1).


So, using bit-mask we can access individual bits [examples]. Sometimes, this technique may also be used for improving performance. Take this for example-

bool isOdd(int i) {
    return i%2;
}

This function tells if an integer is odd/even. We can achieve the same result with more efficiency using bit-mask-

bool isOdd(int i) {
    return i&1;
}

Short Explanation: If the least significant bit of a binary number is 1 then it is odd; for 0 it will be even. So, by doing AND with 1 we are removing all other bits except for the least significant bit i.e.:

     55  ->  0 0 1 1 0 1 1 1   [input]
(&)   1  ->  0 0 0 0 0 0 0 1    [mask]
---------------------------------------
      1  <-  0 0 0 0 0 0 0 1  [output]
Share:
414,896

Related videos on Youtube

Mr.Z
Author by

Mr.Z

Updated on July 08, 2022

Comments

  • Mr.Z
    Mr.Z almost 2 years

    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.

  • Paul R
    Paul R almost 12 years
    Good answer but masking can also be applied for setting or toggling specific bits with OR or XOR operations and a suitable mask.
  • Paul R
    Paul R almost 12 years
    @Mr.Z: in C, C++ and related languages you would you the bitwise AND operator, which is written as &.
  • Lundin
    Lundin almost 12 years
    @Mr.Z For example: clear one byte of a uint32_t by masking the contents away: #define MASK 0x000000FF .... my_uint32_t &= ~MASK.
  • Ungeheuer
    Ungeheuer almost 7 years
    the b to indicate binary literal is not supported by all compilers, correct?
  • Harshit Sharma
    Harshit Sharma about 5 years
    Also, to convert an integer to an odd no. if it is an even number: i=i|1. This comes in handy when we are trying to generate a sequence like 1, 3, 5,..., 2, 4, 6,...
  • Harshit Sharma
    Harshit Sharma about 5 years
    You can also use the following operation to find the number with only the least significant bit from an integer: lsb = i&-i
  • nurabha
    nurabha almost 5 years
    A part of confusion arises possibly because of poor choice of noun and verbs to describe what is really going on. For example, wouldn't a word like "Bitselector" or "TargetBits" seem more suitable word to describe the object instead of using the word "Bitmask" ? Similarly, to describe the bit manipulation operations, using word such as "BitManipulate" seems more suitable word than the word "Masking" as the latter only makes sense for AND operations but not for XORING (toggle bits) or OR (set bits) which are rather bit manipulations or transformations but not masking operation.
  • Margach Chris
    Margach Chris over 4 years
    so a mask is a byte used in a bitwise operation? why call it a "mask?"
  • Jerry An
    Jerry An about 3 years
  • Naman Durve
    Naman Durve about 2 years
    Suppose I used a bit mask in this way " if (value & 0x0F) ". And, suppose if I wanted to use this 'value' variable later, what would the variable 'value' contain? Will it contain it's original data or altered data after the masking operation?