Quiz Entry - updated: 2026.07.07
How do you extract specific bits from an integer?
Shift the wanted bits down to position 0, then AND with a mask of the right number of 1s (or mask first, then shift down).
To extract bits [high:low] from x:
// Method 1: Shift then mask
int bits = (x >> low) & ((1 << (high - low + 1)) - 1);
// Method 2: Mask then shift
int mask = ((1 << (high + 1)) - 1) - ((1 << low) - 1);
int bits = (x & mask) >> low;
Example: Extract bits [5:3] from 0xAB = 10101011:
Bits 5-3 are: 101
(0xAB >> 3) & 0x7 = 0x15 & 0x7 = 0x5
Tip: (1 << n) - 1 creates a mask of n ones.