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.
INT_MINhas no positive counterpart, soabs(INT_MIN)overflows (same as the libraryabs).- 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.
Related
branchless-programming · bit-manipulation · stephan-brumme · xor-swap · bit-twiddling-hacks