C Bitwise Operator Masking

Bitwise Operations and Masking in C Programming

We have learnt different Bitwise Operation Techniques, in this chapter we are going to learn the masking technique to set particular bit on or off.

Masking is the process or operation to set bit on to off or off to on in a byte,nibble or word.
  1. Mask means to block.
  2. Masking is the process by which ,only required data is retained and the rest is masked (blocked)
  3. Masking can be done using Bitwise Operators
  4. Most Commonly Used Bitwise Operator is AND(&)

A. Masking bits to 1 :

  1. In this case we need to retain the particular data.
  2. Bitwise OR Operator is used for masking bits to 1

Truth table for Bitwise OR :

Bit 1 Bit 2 Bitwise OR
0 0 0
1 1 1
0 1 1
1 0 1
We can summarize above table as -
Bit 1 Bit 2 Bitwise OR
1 Y 1
0 Y Y

Live Example : Masking Bits to 1

10011101   10010101
00001000   00001000   OR
-----------------------------
10011101   10011101

B. Masking bits to 0 :

In this case we need to remove data by masking it to 0

Truth table for Bitwise AND :

Bit 1 Bit 2 Bitwise AND
0 0 0
1 1 1
0 1 0
1 0 0
We can summarize above table as -
Bit 1 Bit 2 Bitwise AND
1 Y 1
0 Y Y

Masking or Hiding the Last 4 LSB Bits :

Process of Masking : We want Last 4 LSB Bits , So Mask it with (0000 0000 0000 1111)

Num 1  : 1000 0001 1110 1011 
    &  : 0000 0000 0000 1111
--------------------------------
Result : 0000 0000 0000 1011

We get Result as :-

Num 1 : 0000 0000 0000 1011 // First 12 bits are Masked

Important Topics :


Conclusion of Masking :

  1. Portion to be retained is ANDed with 1
  2. Portion to be Masked is ANDed with 0