Bit masking involves applying a specific binary pattern (the mask) to a value using logical operators to isolate or modify specific bits without affecting others.
AND (&) for Testing: To check if a specific bit is '1', apply a mask with a '1' in that position and '0's elsewhere. If the result is non-zero, the bit is set.
OR (|) for Setting: To force a specific bit to '1', use a mask with a '1' in the target position. This is used to turn on specific device features.
XOR (^) for Toggling: To flip a bit (0 to 1 or 1 to 0), use a mask with a '1' in that position. This is ideal for switching device states back and forth.
| Feature | Logical Shift | Arithmetic Shift | Cyclic Shift |
|---|---|---|---|
| Empty Fill | Always fills with 0 | Fills with Sign Bit (Right) | Fills with wrapped bits |
| Data Loss | Bits are discarded | Bits are discarded | No bits are lost |
| Primary Use | Unsigned Math | Signed Math (Two's Comp) | Cryptography/Rotation |
The choice between AND and OR masking depends on the goal: use AND to 'filter' or 'hide' bits, and use OR to 'inject' or 'activate' bits within a pattern.
Check the Number Type: Always identify if the question specifies 'unsigned' or 'signed' integers. For signed integers, a right shift MUST be arithmetic to maintain the correct value.
Overflow Awareness: In a left shift, if a '1' is shifted out of the MSB position, an overflow error occurs, and the resulting value will no longer represent a simple multiplication by two.
Mask Construction: When asked to 'clear' a bit (set it to 0), the most common method is to use an AND operation with a mask where the target bit is 0 and all other bits are 1.
Verification: After a shift, convert the binary back to denary to ensure the result matches the expected multiplication or division (e.g., shifting left twice should quadruple the value).