POPCNT

Return the Count of Number of Bits Set to 1

Opcodes

Hex Mnemonic Encoding Long Mode Legacy Mode Description
F3 REX.W 0F B8 /r POPCNT r64, r/m64 A Valid N.E. POPCNT on r/m64
F3 0F B8 /r POPCNT r32, r/m32 A Valid Valid POPCNT on r/m32
F3 0F B8 /r POPCNT r16, r/m16 A Valid Valid POPCNT on r/m16

Instruction Operand Encoding

Op/En Operand 0 Operand 1 Operand 2 Operand 3
A NA NA ModRM:r/m (r) ModRM:reg (w)

Description

This instruction calculates of number of bits set to 1 in the second operand (source) and returns the count in the first operand (a destination register).

Pseudo Code

Count = 0;
For (i = 0;
i < OperandSize;
i++)
{
IF (SRC[i] = 1) (* i'th bit *)
	Count++;
FI;
} DEST = Count;

Flags Affected

OF, SF, ZF, AF, CF, PF are all cleared. ZF is set if SRC = 0, otherwise ZF is cleared

Exceptions

64-Bit Mode Exceptions

Exception Description
#UD If CPUID.01H:ECX.POPCNT [Bit 23] = 0. If LOCK prefix is used. Either the prefix REP (F3h) or REPN (F2H) is used.
#PF (fault-code) For a page fault.
#SS(0) If a memory address referencing the SS segment is in a non- canonical form.
#GP(0) If the memory address is in a non-canonical form.

Compatibility Mode Exceptions

Same exceptions as in Protected Mode.

Virtual-8086 Mode Exceptions

Exception Description
#UD If CPUID.01H:ECX.POPCNT [Bit 23] = 0. If LOCK prefix is used. Either the prefix REP (F3h) or REPN (F2H) is used.
#PF (fault-code) For a page fault.
#SS(0) If a memory operand effective address is outside the SS segment limit.
#GP(0) If any part of the operand lies outside of the effective address space from 0 to 0FFFFH.

Real-Address Mode Exceptions

Exception Description
#UD If CPUID.01H:ECX.POPCNT [Bit 23] = 0. If LOCK prefix is used. Either the prefix REP (F3h) or REPN (F2H) is used.
#SS(0) If a memory operand effective address is outside the SS segment limit.
#GP(0) If any part of the operand lies outside of the effective address space from 0 to 0FFFFH.

Protected Mode Exceptions

Exception Description
#UD If CPUID.01H:ECX.POPCNT [Bit 23] = 0. If LOCK prefix is used. Either the prefix REP (F3h) or REPN (F2H) is used.
#PF (fault-code) For a page fault.
#SS(0) If a memory operand effective address is outside the SS segment limit.
#GP(0) If a memory operand effective address is outside the CS, DS, ES, FS or GS segments.