bsf

Bit scan forward

Searches the source for its least significant set bit and, if one is found, stores its index in the destination.

386 and later

Intel's reference: BSF

CFPFAFZFSFDFOF ???●?–?
  • ● set from the result
  • ? undefined afterwards
  • – not changed

Forms

Operands

reg
A general-purpose register matching the operation’s size, for example al, ax, eax or rax. The byte registers ah, bh, ch and dh cannot be used with a REX prefix, which is required by spl, bpl, sil, dil and r8–r15.
r/m
A general-purpose register or memory location matching the operation’s size, for example rax or qword [rbp-8]. The byte registers ah, bh, ch and dh cannot be used with a REX prefix, including when the memory address uses r8–r15.

bsf finds the least significant set bit; bsr finds the most significant. The operands have matching 16-, 32- or 64-bit widths, with indices 0–15, 0–31 or 0–63 respectively.

If the source is zero, ZF is set and the destination should be treated as undefined: current processors leave it as it was, but older ones made no such promise, and some clear the upper half of a 64-bit register even then. Otherwise ZF is cleared, and a 32-bit destination write clears the upper half of its 64-bit register.

global _start

section .text
_start:
        mov rax, 12
        mov rbx, 5
        mov rcx, 3
        mov rsi, 9

        bsf rax, rbx

        mov rax, 60         ; syscall 60: exit
        xor rdi, rdi
        syscall