C Bitwise Operator Masking
Contents
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.
- Mask means to block.
- Masking is the process by which ,only required data is retained and the rest is masked (blocked)
- Masking can be done using Bitwise Operators
- Most Commonly Used Bitwise Operator is AND(&)
A. Masking bits to 1 :
- In this case we need to retain the particular data.
- 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 |
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 |
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 :
Must Read Articles :
Conclusion of Masking :
- Portion to be retained is ANDed with 1
- Portion to be Masked is ANDed with 0