Intrinsics1 min read
count_bits
Counts the number of set bits (population count).
Reading Time
1 min
Word Count
158
Sections
12
Try It Live
Test count_bits in a live shader
Open the playground, start from a visual preset, and wire count_bits into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The count_bits function returns the number of bits set to 1 in an integer value, also known as the population count or Hamming weight.
Signature
bwsl
count_bits :: (int x) -> int {...}
count_bits :: (uint x) -> int {...}
Parameters
| Parameter | Type | Description |
|---|---|---|
x | int or uint | The value to count bits in |
Return Value
Returns the number of 1 bits in x.
Example
bwsl
pipeline VisibilityCount {
pass "Main" {
compute "Main" [64, 1, 1] {
// Count visible objects in bitmask
uint visibilityMask = loadVisibilityMask(tileId);
int visibleCount = count_bits(visibilityMask);
// Allocate space for visible objects
int startIndex = atomic_add(totalVisible[0], visibleCount);
// Process visible objects
processVisible(tileId, startIndex, visibilityMask);
}
}
}Common Use Cases
Counting Set Flags
bwsl
// Count active flags
int activeCount = count_bits(flagBitmask);Voting
bwsl
// Count lanes with condition true
uint ballot = waveBallot(condition);
int trueCount = count_bits(ballot);Sparse Data
bwsl
// Count non-zero elements in packed data
int elementCount = count_bits(occupancyMask);Hamming Distance
bwsl
// Count differing bits between two values
int difference = count_bits(a ^ b);Prefix Sum Building Block
bwsl
// Count bits before position for exclusive prefix
uint mask = (1u << position) - 1u;
int prefixCount = count_bits(value & mask);Hardware Support
Most modern GPUs have a dedicated instruction for population count, making this operation very efficient.
Ballot + Count
Combining wave ballot with count_bits is a common pattern to count how many lanes meet a condition.
Compiled Output
When compiled to GLSL:
glsl
bitCount(x)
When compiled to HLSL:
hlsl
countbits(x)
When compiled to Metal:
metal
popcount(x)
When compiled to SPIR-V:
Uses OpBitCount instruction.
See Also
- first_bit_low - Find lowest set bit
- first_bit_high - Find highest set bit
- reverse_bits - Reverse bit order