count_bits
Counts the number of set bits (population count).
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
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
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
// Count active flags
int activeCount = count_bits(flagBitmask);Voting
// Count lanes with condition true
uint ballot = waveBallot(condition);
int trueCount = count_bits(ballot);Sparse Data
// Count non-zero elements in packed data
int elementCount = count_bits(occupancyMask);Hamming Distance
// Count differing bits between two values
int difference = count_bits(a ^ b);Prefix Sum Building Block
// 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.
Known issue: uint in WebGL output
The GLSL ES output for count_bits on a uint currently fails to compile in WebGL, because GLSL's bitCount returns int (BWSL#213). Other targets are unaffected. For WebGL, pass an int until this is fixed.
Compiled Output
When compiled to GLSL:
bitCount(x)
When compiled to HLSL:
countbits(x)
When compiled to 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