User Guide
54 General-Purpose Programming
AMD64 Technology 24592—Rev. 3.15—November 2009
The CMP instruction is often used together with the conditional jump instructions (Jcc), conditional
SET instructions (SETcc) and other instructions such as conditional loops (LOOPcc) whose behavior
depends on flag state.
Test
• TEST—Test Bits
The TEST instruction is in many ways similar to the AND instruction: it performs logical conjunction
of the corresponding bits of both operands, but unlike the AND instruction it leaves the operands
unchanged. The purpose of this instruction is to update flags for further testing.
The TEST instruction is often used to test whether one or more bits in an operand are zero. In this case,
one of the instruction operands would contain a mask in which all bits are cleared to zero except t he
bits being tested. For more advanced bit testing and bit modification, use the BTx instructions.
Bit Scan
• BSF—Bit Scan Forward
• BSR—Bit Scan Reverse
The BSF and BSR instructions search a source operand for the least-significant (BSF) or most-
significant (BSR) bit that is set to 1. If a set bit is found, its bit index is loaded into the destination
operand, and the zero flag (ZF) is set. If no set bit is found, the zero flag is cleared and the contents of
the destination are undefined.
Population and Leading Zero Counts
• POPCNT—Bit Population Count
• LZCNT—Count Leading Zeros
The POPCNT instruction counts the number of bits having a value of 1 in the source operand and
places the total in the destination register, while the LZCNT instruction counts the number of leading
zero bits in a general purpose register or memory source operand.
Bit Test
• BT—Bit Test
• BTC—Bit Test and Complement
• BTR—Bit Test and Reset
• BTS—Bit Test and Set
The BTx instructions copy a specified bit in the first operand to the carry flag (CF) and leave the source
bit unchanged (BT), or complement the source bit (BTC), or clear the source bit to 0 (BTR), or set the
source bit to 1 (BTS).
These instructions are useful for implementing semaphore arrays. Unlike the XCHG instruction, the
BTx instructions set the carry flag, so no additional test or compare instruction is needed. Also,