Skip to content

Instructions

x86-64

BT / BTS / BTR / BTC (bit test)

Test, set, reset or complement a single bit selected by index, capturing the old value in the carry flag. The compact way to manipulate bitfields and flags.

The bit-test family selects one bit of an operand by index and reports its previous value in CF. They differ only in what they do to that bit afterwards:

InstrAction on the selected bitMnemonic for
BTleave unchangedtest
BTSset to 1test-and-set
BTRclear to 0test-and-reset
BTCtoggletest-and-complement
asm
bt  eax, 3        ; CF = bit 3 of eax           (read)
bts eax, 3        ; CF = old bit 3; then set it
btr eax, 3        ; CF = old bit 3; then clear it
btc eax, 3        ; CF = old bit 3; then flip it

The bit index can be an immediate or a register, and the destination can be a register or memory.

A subtle memory addressing rule

When the destination is memory and the index is a register, the bit offset is not masked to the operand size — the CPU computes address + (index / 8) and indexes the bit within that byte. This lets bt address a bit in an arbitrarily large in-memory bitmap with a single instruction, but it also means bts [rax], rcx can touch memory far from [rax]. Disassemblers and decompilers sometimes model this imprecisely, so verify by hand when a bt* touches memory.

Reverse-engineering notes

  • A bt reg, imm followed by jc/jnc (or setc) is a clean "is flag N set?" test against a bitmask register — typical of permission flags, feature bits, and state machines. The immediate is the bit number.
  • Compilers often prefer the plain bitwise equivalents because they're faster on most cores: test eax, (1<<3) to test, or/and/xor with a mask to set/clear/toggle. So a literal bt* frequently signals hand-written assembly, intrinsics (_bittest), or size-optimised code.
  • bts/btr on a memory operand with a lock prefix is an atomic bit operation — the building block for spinlocks and lock-free bitsets. Spotting lock bts points straight at concurrency code.

See also: AND / OR / NOT · Shift & rotate · BSF / BSR & population count · RFLAGS.