SYSTEMS / Learn
Saved on this device>
← Back to goals

I want to…

Set the rightmost zero bit

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 | (x + 1)8-bit word · arithmetic wraps modulo 256
BIT-BY-BIT WALKTHROUGH
OperatorBits 7 → 0Decimal
x1001 10012153
x + 11001 10102154
Result1001 10112155

Adding one carries through the trailing ones and sets the first zero above them. OR with x restores the trailing ones. Therefore x | (x + 1) gives 10011011. If all eight bits are already 1, x + 1 wraps to 0 and the word stays 255.

IN CODEC17
#include <stdint.h>
uint8_t x = 153;

uint8_t result = x | (uint8_t)(x + 1u);

C17 · snippets use uint8_t from <stdint.h>. Casts keep the low 8 bits; shifts use unsigned operands. Run the statements inside a function.

Hacker’s Delight · §2-1

coffee-bytes / Systems LearningCS:APP + Hacker’s Delight