Skip to content
systemcoding.dev
Assembly

Turn a comparison into 0 or 1 with setne and movzx

Turn a flag into 0 or 1 with setne al and movzx eax, al: clear the register first only if the flags are not live. NASM 2.16, x86-64.

1 min read
Summarize in AI

This is how you turn a comparison into a plain integer 0 or 1, the way a C compiler lowers return a != b. setne writes only the low byte of its destination, so the rest of the register must be dealt with. movzx after the setne zero-extends it and costs one extra instruction on the dependency chain.

ne.asmasm
bits 64
global ne64
ne64:                   ; int ne64(long a, long b)
    cmp rdi, rsi
    setne al
    movzx eax, al
    ret
Text
ne64(5, 7)  -> eax = 1
ne64(9, 9)  -> eax = 0

The alternative is to clear eax with xor eax, eax before the cmp and then setne al, which removes the movzx from the critical path. The xor has to come before the cmp, because it rewrites the flags. Intel documents SETcc as writing one byte in the SDM instruction reference. If the register is already in use, stay with movzx.

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.