Intrinsics1 min read

first_bit_low

Finds the position of the lowest set bit.

Reading Time
1 min
Word Count
157
Sections
12
Try It Live

Test first_bit_low in a live shader

Open the playground, start from a visual preset, and wire first_bit_low into the fragment stage to see how it behaves with real values.

Open Playground

Live Demo

The first_bit_low function returns the bit position of the lowest (least significant) bit that is set to 1.

Signature

bwsl
first_bit_low :: (int x) -> int {...}
first_bit_low :: (uint x) -> int {...}

Parameters

ParameterTypeDescription
xint or uintThe value to examine

Return Value

Returns the zero-based position of the lowest set bit, or -1 (or 32/0xFFFFFFFF) if no bits are set.

Example

bwsl
pipeline ProcessBitmask {
pass "Main" {
compute "Main" [64, 1, 1] {
// Process each set bit in the mask
uint mask = activeMask;
while (mask != 0u) {
// Find lowest set bit
int bitPos = first_bit_low(mask);
// Process item at this bit position
processItem(bitPos);
// Clear the processed bit
mask &= ~(1u << bitPos);
}
}
}
}

Common Use Cases

Iterate Set Bits

bwsl
// Process all set bits efficiently
while (mask != 0) {
int bit = first_bit_low(mask);
doSomething(bit);
mask &= mask - 1; // Clear lowest bit
}

Power of 2 Check

bwsl
// Check if exactly one bit is set
bool isPowerOf2 = first_bit_low(x) == first_bit_high(x);

Trailing Zeros

bwsl
// Count trailing zeros (bits after lowest set bit)
int trailingZeros = first_bit_low(x);

Alignment Check

bwsl
// Check alignment (power of 2)
int alignment = 1 << first_bit_low(address);

Priority Queue

bwsl
// Find highest priority (lowest bit = highest priority)
int highestPriority = first_bit_low(priorityMask);

Zero Input

When x is 0, the result is implementation-defined (typically -1 or 32). Always check for zero if it's a possibility.

Clear Lowest Bit

To clear the lowest set bit: x &= x - 1. This is faster than x &= ~(1 << first_bit_low(x)).

Compiled Output

When compiled to GLSL:

glsl
findLSB(x)

When compiled to HLSL:

hlsl
firstbitlow(x)

When compiled to Metal:

metal
ctz(x)  // Count trailing zeros

When compiled to SPIR-V:

Uses GLSLstd450FindILsb extended instruction.

See Also