Spokes.wiki Search Graph Growth About

bit-manipulation-wiki

Tech Article source ↗ source url updated Mon Jun 15 2026 00:00:00 GMT+0000 (Coordinated Universal Time)

Branchless absolute value (Stephan Brumme, bits)

stephan-brumme‘s page on computing the absolute value of an integer without a branch, from his benchmarked bits collection.

The trick

Use the arithmetic-shifted sign bit as a mask instead of a conditional. For a 32-bit int x:

mask = x >> 31;        // all 1s if negative, all 0s if non-negative (arithmetic shift)
abs  = (x ^ mask) - mask;

When x ≥ 0, mask = 0 and the result is x; when x < 0, mask = -1, which flips the bits and adds 1 — two’s-complement negation. No data-dependent branch, so no pipeline mispredict.

Caveats

Why it’s here

A textbook instance of branchless-programming: replace a conditional with sign-bit arithmetic. Pairs with xor-swap (same author, same “elegant but usually superseded” arc) and the sign/min/max family in bit-twiddling-hacks.

Tier

T2 — author-maintained technical reference with disassembly + benchmarks; single-author, self-published; figures are dated CPU/compiler snapshots.

branchless-programming · bit-manipulation · stephan-brumme · xor-swap · bit-twiddling-hacks