What is Bit Masking?
What is Bit Masking?
Bit masking is a technique used in computer programming to manipulate specific bits within a binary number. It involves applying a mask to a value to keep, change, or clear certain bits. This is achieved using bitwise operations such as AND, OR, XOR, and NOT.
Mask Definition: A mask is a binary number that specifies which bits in another binary number should be kept, changed, or cleared. For example, a mask of 00001111
would focus on the lower four bits of a byte.
Bitwise Operations:
&
): Used to clear bits. Only the bits that are 1 in both the mask and the value remain 1.|
): Used to set bits. Any bit that is 1 in the mask will be set to 1 in the value.^
): Used to toggle bits. Bits that are 1 in the mask will be flipped in the value.~
): Used to invert bits. All 0s become 1s and all 1s become 0s.Setting a Bit:
To set a specific bit to 1, use the OR operation with a mask that has a 1 at the bit position you want to set.
value |= (1 << bit_position);
Example: To set the 3rd bit of 01000010
:
01000010
OR
00001000
------
01001010
Clearing a Bit:
To clear a specific bit to 0, use the AND operation with a mask that has a 0 at the bit position you want to clear.
value &= ~(1 << bit_position);
Example: To clear the 3rd bit of 01001010
:
01001010
AND
11110111
------
01000010
Toggling a Bit:
To toggle a specific bit, use the XOR operation with a mask that has a 1 at the bit position you want to toggle.
value ^= (1 << bit_position);
Example: To toggle the 3rd bit of 01000010
:
01000010
XOR
00001000
------
01001010
Checking a Bit:
To check if a specific bit is set, use the AND operation with a mask that has a 1 at the bit position you want to check.
bit = value & (1 << bit_position);
Example: To check the 3rd bit of 01001010
:
01001010
AND
00001000
------
00001000
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào