Find first set


In computer software and hardware, find first set or find first one is a bit operation that, given an unsigned machine word, designates the index or position of the least significant bit set to one in the word counting from the least significant bit position. A nearly equivalent operation is count trailing zeros or number of trailing zeros, which counts the number of zero bits following the least significant one bit. The complementary operation that finds the index or position of the most significant set bit is log base 2, so called because it computes the binary logarithm. This is [|closely related] to count leading zeros or number of leading zeros, which counts the number of zero bits preceding the most significant one bit.
There are two common variants of find first set, the POSIX definition which starts indexing of bits at 1, herein labelled ffs, and the variant which starts indexing of bits at zero, which is equivalent to ctz and so will be called by that name.
Most modern CPU instruction set architectures provide one or more of these as hardware operators; software emulation is usually provided for any that aren't available, either as compiler intrinsics or in system libraries.

Examples

Given the following 32-bit word:
The count trailing zeros operation would return 3, while the count leading zeros operation returns 16. The count leading zeros operation depends on the word size: if this 32-bit word were truncated to a 16-bit word, count leading zeros would return zero. The find first set operation would return 4, indicating the 4th position from the right. The log base 2 is 15.
Similarly, given the following 32-bit word, the bitwise negation of the above word:
The count trailing ones operation would return 3, the count leading ones operation would return 16, and the find first zero operation ffz would return 4.
If the word is zero, count leading zeros and count trailing zeros both return the number of bits in the word, while ffs returns zero. Both log base 2 and zero-based implementations of find first set generally return an undefined result for the zero word.

Hardware support

Many architectures include instructions to rapidly perform find first set and/or related operations, listed below. The most common operation is count leading zeros, likely because all other operations can be implemented efficiently in terms of it.
PlatformMnemonicNameOperand widthsDescriptionOn application to 0
ARM
except Cortex-M0/M0+/M1/M23
clzCount Leading Zeros32clz32
ARM clzCount Leading Zeros32, 64clzOperand width
AVR32clzCount Leading Zeros32clz32
DEC AlphactlzCount Leading Zeros64clz64
DEC AlphacttzCount Trailing Zeros64ctz64
Intel 80386 and laterbsfBit Scan Forward16, 32, 64ctzUndefined; sets zero flag
Intel 80386 and laterbsrBit Scan Reverse16, 32, 64Log base 2Undefined; sets zero flag
x86 supporting BMI1 or ABMlzcntCount Leading Zeros16, 32, 64clzOperand width; sets carry flag
x86 supporting BMI1tzcntCount Trailing Zeros16, 32, 64ctzOperand width; sets carry flag
ItaniumclzCount Leading Zeros64clz64
MIPSclzCount Leading Zeros in Word32, 64clzOperand width
MIPScloCount Leading Ones in Word32, 64cloOperand width
Motorola 68020 and laterbfffoFind First One in Bit FieldArbitraryLog base 2Field offset + field width
PDP-10jffoJump if Find First One36ctz0; no operation
POWER/PowerPC/Power ISAcntlz/cntlzw/cntlzdCount Leading Zeros32, 64clzOperand width
Power ISA 3.0 and latercnttzw/cnttzdCount Trailing Zeros32, 64ctzOperand width
RISC-V clzCount Leading Zeros32, 64clzOperand width
RISC-V ctzCount Trailing Zeros32, 64ctzOperand width
SPARC Oracle Architecture 2011 and laterlzcnt Leading Zero Count64clz64
VAXffsFind First Set0–32ctzOperand width; sets zero flag
IBM z/ArchitectureflogrFind Leftmost One64clz64
IBM z/ArchitecturevclzVector Count Leading Zeroes8, 16, 32, 64clzOperand width
IBM z/ArchitecturevctzVector Count Trailing Zeroes8, 16, 32, 64ctzOperand width

On some Alpha platforms CTLZ and CTTZ are emulated in software.

Tool and library support

A number of compiler and library vendors supply compiler intrinsics or library functions to perform find first set and/or related operations, which are frequently implemented in terms of the hardware instructions above:
Tool/libraryNameTypeInput typeNotesOn application to 0
POSIX.1 compliant libc
4.3BSD libc
OS X 10.3 libc
ffsLibrary functionintIncludes glibc. POSIX does not supply the complementary log base 2 / clz.0
FreeBSD 5.3 libc
OS X 10.4 libc
ffsl
fls
flsl
Library functionint,
long
fls computes + 1.0
FreeBSD 7.1 libcffsll
flsll
Library functionlong long0
GCC 3.4.0
Clang 5.x
__builtin_ffs
__builtin_clz
__builtin_ctz
Built-in functionsunsigned int,
unsigned long,
unsigned long long,
uintmax_t
GCC documentation considers result undefined clz and ctz on 0.0
Visual Studio 2005_BitScanForward
_BitScanReverse
Compiler intrinsicsunsigned long,
unsigned __int64
Separate return value to indicate zero inputUndefined
Visual Studio 2008__lzcntCompiler intrinsicunsigned short,
unsigned int,
unsigned __int64
Relies on hardware support for the lzcnt instruction introduced in BMI1 or ABM.Operand width
Intel C++ Compiler_bit_scan_forward
_bit_scan_reverse
Compiler intrinsicsintUndefined
NVIDIA CUDA__clzFunctions32-bit, 64-bitCompiles to fewer instructions on the GeForce 400 Series32
NVIDIA CUDA__ffsFunctions32-bit, 64-bitCompiles to fewer instructions on the GeForce 400 Series0
LLVMllvm.ctlz.*
llvm.cttz.*
Intrinsic8, 16, 32, 64, 256LLVM assembly languageOperand width, if 2nd argument is 0; undefined otherwise
GHC 7.10, in Data.BitscountLeadingZeros
countTrailingZeros
Library functionFiniteBits b => bHaskell programming languageOperand width
C++20 standard library, in header bit_ceil bit_floor
bit_width
countl_zero countl_one
countr_zero countr_one
Library functionunsigned char,
unsigned short,
unsigned int,
unsigned long,
unsigned long long

Properties and relations

If bits are labeled starting at 1, then count trailing zeros and find first set operations are related by . If bits are labeled starting at, then count trailing zeros and find first set are exactly equivalent operations. Given bits per word, the is easily computed from the and vice versa by.
As demonstrated in the example above, the find first zero, count leading ones, and count trailing ones operations can be implemented by negating the input and using find first set, count leading zeros, and count trailing zeros. The reverse is also true.
On platforms with an efficient log2 operation such as M68000, can be computed by:
where denotes bitwise AND and denotes the two's complement of. The expression clears all but the least-significant bit, so that the most- and least-significant bit are the same.
On platforms with an efficient count leading zeros operation such as ARM and PowerPC, can be computed by:
Conversely, on machines without or operators, can be computed using, albeit inefficiently:
On platforms with an efficient Hamming weight operation such as SPARC's POPC or Blackfin's ONES, there is:
where denotes bitwise exclusive-OR and denotes bitwise negation.
The inverse problem can be computed with a left-shift.
Find first set and related operations can be extended to arbitrarily large bit arrays in a straightforward manner by starting at one end and proceeding until a word that is not all-zero or not all-one is encountered. A tree data structure that recursively uses bitmaps to track which words are nonzero can accelerate this.

Software emulation

Most CPUs dating from the late 1980s onward have bit operators for ffs or equivalent, but a few modern ones like some of the ARM-Mx series do not. In lieu of hardware operators for ffs, clz and ctz, software can emulate them with shifts, integer arithmetic and bitwise operators. There are several approaches depending on architecture of the CPU and to a lesser extent, the programming language semantics and compiler code generation quality. The approaches may be loosely described as linear search, binary search, search+table lookup, de Bruijn multiplication, floating point conversion/exponent extract, and bit operator methods. There are tradeoffs between execution time and storage space as well as portability and efficiency.
Software emulations are usually deterministic. They return a defined result for all input values; in particular, the result for an input of all zero bits is usually 0 for ffs, and the bit length of the operand for the other operations.
If one has a hardware clz or equivalent, ctz can be efficiently computed with bit operations, but the converse is not true: clz is not efficient to compute in the absence of a hardware operator.

2n

The function using shifts and bitwise ORs is not efficient to compute as in this 32-bit example and even more inefficient if we have a 64-bit or 128-bit operand:
function pow2:
if x = 0 return invalid // invalid is implementation defined
x ← x - 1
for each y in : x ← x |
return x + 1

FFS

Since ffs = ctz + 1 or ffs = ctz, the applicable algorithms for ctz may be used, with a possible final step of adding 1 to the result, and returning 0 instead of the operand length for input of all zero bits.

CTZ

The canonical algorithm is a loop counting zeros starting at the LSB until a 1-bit is encountered:
function ctz1
if x = 0 return w
t ← 1
r ← 0
while = 0
t ← t << 1
r ← r + 1
return r
This algorithm executes O time and operations, and is impractical in practice due to a large number of conditional branches.
A lookup table can eliminate most branches:
table = ctz for i in 0..2n-1
function ctz2
if x = 0 return w
r ← 0
loop
if ≠ 0
return r + table
x ← x >> n
r ← r + n
The parameter n is fixed and represents a time–space tradeoff. The loop may also be fully unrolled. But as a linear lookup, this approach is still O in the number of bits in the operand.
A binary search implementation takes a logarithmic number of operations and branches, as in this 32-bit version:
This algorithm can be assisted by a table as well, replacing the bottom three "if" statements with a 256 entry lookup table using the first non-zero byte encountered as an index.
function ctz3
if x = 0 return 32
n ← 0
if = 0: n ← n + 16, x ← x >> 16
if = 0: n ← n + 8, x ← x >> 8
if = 0: n ← n + 4, x ← x >> 4
if = 0: n ← n + 2, x ← x >> 2
if = 0: n ← n + 1
return n
If the hardware has a clz operator, the most efficient approach to computing ctz is thus:
function ctz4
x &= -x
return w -
An algorithm for 32-bit ctz uses de Bruijn sequences to construct a minimal perfect hash function that eliminates all branches.
This algorithm assumes that the result of the multiplication is truncated to 32 bit.
for i from 0 to 31: table ← i // table initialized
function ctz5
return table
The expression again isolates the least-significant 1 bit. There are then only 32 possible words, which the unsigned multiplication and shift hash to the correct position in the table.

CLZ

The canonical algorithm examines one bit at a time starting from the MSB until a non-zero bit is found, as shown in this example. It executes in O time where n is the bit-length of the operand, and is not a practical algorithm for general use.
function clz1
if x = 0 return w
t ← 1 << w - 1
r ← 0
while = 0
t ← t >> 1
r ← r + 1
return r
An improvement on the previous looping approach examines eight bits at a time then uses a 256 entry lookup table for the first non-zero byte. This approach, however, is still O in execution time.
function clz2
if x = 0 return w
t ← 0xff << w - 8
r ← 0
while = 0
t ← t >> 8
r ← r + 8
return r + table
Binary search can reduce execution time to O:
function clz3
if x = 0 return 32
n ← 0
if = 0: n ← n + 16, x ← x << 16
if = 0: n ← n + 8, x ← x << 8
if = 0: n ← n + 4, x ← x << 4
if = 0: n ← n + 2, x ← x << 2
if = 0: n ← n + 1
return n
The fastest portable approaches to simulate clz are a combination of binary search and table lookup: an 8-bit table lookup can replace the bottom 3 branches in binary search. 64-bit operands require an additional branch. A larger width lookup can be used but the maximum practical table size is limited by the size of L1 data cache on modern processors, which is 32 KB for many. Saving a branch is more than offset by the latency of an L1 cache miss.
An algorithm similar to de Bruijn multiplication for CTZ works for CLZ, but rather than isolating the most-significant bit, it rounds up to the nearest integer of the form 2n−1 using shifts and bitwise ORs:
table =
function clz4
for each y in : x ← x |
return table
For processors with deep pipelines, like Prescott and later Intel processors, it may be faster to replace branches by bitwise AND and OR operators to avoid pipeline flushes for mispredicted branches :
function clz5
r = << 4; x >>= r;
q = << 3; x >>= q; r |= q;
q = << 2; x >>= q; r |= q;
q = << 1; x >>= q; r |= q;
r |= ;
return r;
On platforms that provide hardware conversion of integers to floating point, the exponent field can be extracted and subtracted from a constant to compute the count of leading zeros. Corrections are needed to account for rounding errors. Floating point conversion can have substantial latency. This method is highly non-portable and not usually recommended.

int x;
int r;
union t;
t.u = 0x43300000; // LE is 1 for little-endian
t.u = x;
t.d -= 4503599627370496.0;
r = - 0x3FF; // log2
r++; // CLZ

Applications

The count leading zeros operation can be used to efficiently implement normalization, which encodes an integer as m × 2e, where m has its most significant bit in a known position. This can in turn be used to implement Newton-Raphson division, perform integer to floating point conversion in software, and other applications.
Count leading zeros can be used to compute the 32-bit predicate "x = y" via the identity, where ">>" is unsigned right shift. It can be used to perform more sophisticated bit operations like finding the first string of n 1 bits. The expression is an effective initial guess for computing the square root of a 32-bit integer using Newton's method. CLZ can efficiently implement null suppression, a fast data compression technique that encodes an integer as the number of leading zero bytes together with the nonzero bytes. It can also efficiently generate exponentially distributed integers by taking the clz of uniformly random integers.
The log base 2 can be used to anticipate whether a multiplication will overflow, since.
Count leading zeros and count trailing zeros can be used together to implement Gosper's loop-detection algorithm, which can find the period of a function of finite range using limited resources.
The binary GCD algorithm spends many cycles removing trailing zeros; this can be replaced by a count trailing zeros followed by a shift. A similar loop appears in computations of the hailstone sequence.
A bit array can be used to implement a priority queue. In this context, find first set is useful in implementing the "pop" or "pull highest priority element" operation efficiently. The Linux kernel real-time scheduler internally uses sched_find_first_bit for this purpose.
The count trailing zeros operation gives a simple optimal solution to the Tower of Hanoi problem: the disks are numbered from zero, and at move k, disk number ctz is moved the minimum possible distance to the right. It can also generate a Gray code by taking an arbitrary word and flipping bit ctz at step k.