Bit Manipulation: Shifts and Masks
1. Why Manipulate Individual Bits?
Sometimes a program needs to work below the level of whole numbers — setting a single flag, extracting a colour channel from a pixel, or testing one status bit returned by a device. Bit manipulation provides operations that act on the individual bits of a value, and they are extremely fast because the processor performs them directly.
2. Logical Shifts
A logical shift moves every bit left or right by a given number of places. Vacated positions are filled with 0, and bits shifted off the end are lost.
Logical shift left
Each shift left multiplies by 2. Two places multiplies by 4, three places by 8.
Logical shift right
Each shift right divides by 2, discarding any remainder. 11 ÷ 2 = 5 remainder 1, and that remainder is lost permanently.
3. Arithmetic Shifts
An arithmetic shift is used with signed numbers held in two's complement, where the leftmost bit is the sign bit. To preserve the sign, an arithmetic shift right copies the sign bit into the vacated position instead of inserting a 0.
| Logical shift | Arithmetic shift | |
|---|---|---|
| Used for | Unsigned values | Signed values (two's complement) |
| Shift right fills with | 0 | A copy of the sign bit |
| Shift left fills with | 0 | 0 |
| Effect of right shift | Unsigned divide by 2 | Signed divide by 2, sign kept |
4. Bit Masking
A mask is a carefully chosen binary pattern combined with a value using a logical operator, in order to isolate, set or invert particular bits. The choice of operator determines the effect.
| Goal | Operator | Mask bit | Because |
|---|---|---|---|
| Test / isolate a bit | AND | 1 where you want to keep | X AND 1 = X, X AND 0 = 0 |
| Set a bit to 1 | OR | 1 where you want to set | X OR 1 = 1, X OR 0 = X |
| Invert / toggle a bit | XOR | 1 where you want to flip | X XOR 1 = NOT X, X XOR 0 = X |
Testing a bit with AND
Is bit 2 of 01101101 set? Use a mask with a 1 in position 2 only:
If the result is zero the bit was 0; if non-zero the bit was 1. Every other bit is forced to 0 by the mask, so only the bit of interest can influence the answer.
Setting a bit with OR
Toggling bits with XOR
5. Putting It Together
Extracting the middle 4 bits of an 8-bit value uses a mask followed by a shift:
The mask discards the unwanted bits; the shift moves the remainder down so it can be read as an ordinary number. This is exactly how a colour channel is extracted from a packed pixel value.
6. Exam Focus
Quick self-check
- State the effect on the value of a logical shift left by 4 places.
- Perform a logical shift right by 2 on 10110100.
- Explain why shifting right then left does not restore the original value.
- Give the 8-bit mask and operator needed to test bit 5.
- Give the mask and operator needed to clear bit 0 to zero.
- Why is an arithmetic shift needed for two's complement numbers?