Skip to content
systemcoding.dev
Assembly

Compute a branch-free absolute value with cdq, xor and sub

Compute a branch-free absolute value with cdq, xor and sub: sign-mask the input, flip the bits, add one back. NASM 2.16, x86-64.

1 min read
Summarize in AI

A branch-free absolute value works by building a mask from the sign bit. cdq copies the sign of eax into every bit of edx, so edx is 0 for a non-negative number and -1 for a negative one. Then x xor mask flips all bits when negative, and subtracting the mask adds one, which together are two's-complement negation.

abs32.asmasm
bits 64
global abs32
abs32:                  ; int abs32(int x)
    mov eax, edi
    cdq                 ; edx = sign mask
    xor eax, edx
    sub eax, edx
    ret
Text
abs32(-5)          -> 5
abs32(7)           -> 7
abs32(-2147483648) -> -2147483648

The last line is the limit: the most negative 32-bit value has no positive counterpart, so it comes back unchanged, exactly as C's abs(INT_MIN) is undefined. Note that cdq clobbers edx, which is a caller-saved register in the System V ABI, so nothing needs saving. A cmovl after a neg does the same job with a conditional move; this version has no flag dependence on a prior instruction.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.