first_bit_low
Finds the position of the lowest set bit.
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 PlaygroundLive Demo
The first_bit_low function returns the bit position of the lowest (least significant) bit that is set to 1.
Signature
first_bit_low :: (int x) -> int {...}
first_bit_low :: (uint x) -> int {...}
Parameters
| Parameter | Type | Description |
|---|---|---|
x | int or uint | The 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
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
// 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
// Check if exactly one bit is set
bool isPowerOf2 = first_bit_low(x) == first_bit_high(x);Trailing Zeros
// Count trailing zeros (bits after lowest set bit)
int trailingZeros = first_bit_low(x);Alignment Check
// Check alignment (power of 2)
int alignment = 1 << first_bit_low(address);Priority Queue
// 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:
findLSB(x)
When compiled to HLSL:
firstbitlow(x)
When compiled to Metal:
ctz(x) // Count trailing zeros
When compiled to SPIR-V:
Uses GLSLstd450FindILsb extended instruction.
See Also
- first_bit_high - Find highest set bit
- count_bits - Count set bits