Bit masking is the process of getting the processor to ignore all the bits that we don’t want to work on and only process the digits we want to process. The basic idea behind the bit masking is to use bitwise operations (e.g. AND, OR, XOR, NOT) to change or inspect specific bits in a binary value. You can use multiple operations to perform complex masking.

Basic operations

AND operation

Bitwise AND (&) is used to set specific bits to 0 while preserving others. To set a particular bit to 0, using AND operation with a mask that has all bits set to 1 except the one you want to set to 0.

Example

We want the 2nd last bit of the original value to be 0.

original_value = 0b11011010
mask = 0b11111101  # set the 2nd last to 0, rest are 1s
result = original_value & maks
OUTPUT
result = 0b11011000

OR operation

Bitwise OR (|) is used to set specific bits to 1 while preserving others. To set a particular bit to 1, using OR operation with a mask that has all bits set to 0 except the one you want to set to 1.

Example

We want the last bit of the original value to be 1.

original_value = 0b11011010
mask = 0b00000001  # set the rightmost bit to 1, rest are 0s
result = original_value | mask
OUTPUT
result = 0b11011011

XOR operation

Bitwise XOR (^) is used to flip specific bits while preserving others. With XOR operation we can flip whatever the digit is to its opposite. To flip a particular bit, using XOR operation with a mask that has all bits set to 0 except the one you want to flip.

original_value = 0b11011010
mask = 0b0000010  # flip the 2nd last bit from the right
result = original_value ^ mask
OUTPUT
result = 0b11011000 

The 2nd last bit is flipped from 1 to 0.

NOT operation

Bitwise NOT (~) is used to invert all bits (1s becomes 0s and 0s becomes 1s).

original_value = 0b11011010
result = ~original_value
OUTPUT
result = 0b00100101

Bit checking using AND (&)

Example

In bit checking we want to know if there is value (1) in digit number 3, count from the right.

  1011 1110 <- DATA
& 0000 0100 <- MASK
--------------------
  0000 0100 <- RESULT

After performing the masking we know the value of the digit number 3 is 1. If we want to return a true or false, we can apply the bit shifting, shift the bit to right by 2 units (digit number 3 - 1), and we obtain 0000 0001 and this is the binary value 1 which stands for true.


Operating_systemINFO1112Bit_masking