Spokes.wiki Search About
Tech Article T2 stable source ↗ source url
Created
Updated

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

  • Relies on arithmetic right shift of signed ints (implementation-defined / UB-adjacent in C for signed types) and on two's-complement representation — portable in practice, but not by the letter of the standard. (Updated 2026-09-28: the standards now split this in two. C23 guarantees two's complement (wg14-n2412) but keeps a negative x >> 31 implementation-defined; C++20 guarantees both the representation and the arithmetic shift (p1236-signed-integers-twos-complement). GCC documents sign extension for negative >> (gcc-integers-implementation).)*
  • INT_MIN has no positive counterpart, so abs(INT_MIN) overflows (same as the library abs).
  • Modern compilers already emit branchless abs from the naive x < 0 ? -x : x (conditional-move / dedicated sequences), so the hand-written trick rarely wins today — the same lesson as xor-swap.

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