← Back to goals I want to…
Extract a three-bit field
Trace this example, understand why the operation works, then try it from memory.
1 · Choose a goal → 2 · Learn the method → 3 · Practise → 4 · Spaced review
Learn the method
(x >> 3) & 0x078-bit word · arithmetic wraps modulo 256
BIT-BY-BIT WALKTHROUGH| Operator | Bits 7 → 0 | Decimal |
|---|
x | 1001 10012 | 153 |
|---|
x >> 3 | 0001 00112 | 19 |
|---|
0x07 | 0000 01112 | 7 |
|---|
Result | 0000 00112 | 3 |
|---|
(a >> 3) & 7 isolates the field: 3.
IN CODEC17
#include <stdint.h>
uint8_t x = 153;
uint8_t result = (x >> 3) & 0x07u;
C17 · snippets use uint8_t from <stdint.h>. Casts keep the low 8 bits; shifts use unsigned operands. Run the statements inside a function.
CS:APP · §2.1.8