# `bsf`

[x86-64 Documentation](https://asm-editor.specy.app/documentation/x86.md) › [Instructions](https://asm-editor.specy.app/documentation/x86/instruction.md)

Web page: https://asm-editor.specy.app/documentation/x86/instruction/bsf

**Bit scan forward**

Category: Logic

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](https://intel.github.io/SDM/instruction/BSF.html)

## Flags

| Flag | Effect |
| --- | --- |
| CF | undefined (do not rely on it) |
| PF | undefined (do not rely on it) |
| AF | undefined (do not rely on it) |
| ZF | depends on the result |
| SF | undefined (do not rely on it) |
| DF | not changed |
| OF | undefined (do not rely on it) |

## Forms

- `bsf reg, r/m` (16, 32, 64)
  - `bsf reg16, r/m16`
  - `bsf reg32, r/m32`
  - `bsf reg64, r/m64`

## Operands

- `reg`: A general-purpose register matching the operation’s size, for example `al`, `ax`, `eax` or `rax`.
- `r/m`: A general-purpose register or memory location matching the operation’s size, for example `rax` or `qword [rbp-8]`.

## Description

`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.

## Example

```x86
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
```
