first_bit_high
Finds the position of the highest set bit.
Test first_bit_high in a live shader
Open the playground, start from a visual preset, and wire first_bit_high into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The first_bit_high function returns the bit position of the highest (most significant) bit that is set to 1.
Signature
first_bit_high :: (int x) -> int {...}
first_bit_high :: (uint x) -> int {...}
Parameters
| Parameter | Type | Description |
|---|---|---|
x | int or uint | The value to examine |
Return Value
Returns the zero-based position of the highest set bit, or -1 (or 32/0xFFFFFFFF) if no bits are set.
Example
pipeline MipmapLevel {
pass "Main" {
compute "Main" [64, 1, 1] {
// Calculate mip level from texture dimensions
uint maxDim = max(textureWidth, textureHeight);
int mipLevels = first_bit_high(maxDim) + 1;
// Process each mip level
for (int mip = 0; mip < mipLevels; mip++) {
processMipLevel(mip);
}
}
}
}Common Use Cases
Log2 Calculation
// Integer log base 2
int log2Value = first_bit_high(x);Mipmap Levels
// Number of mip levels for texture
int mips = first_bit_high(max(width, height)) + 1;Power of 2 Rounding
// Round up to next power of 2
int highBit = first_bit_high(x - 1) + 1;
int nextPow2 = 1 << highBit;Bit Width
// Minimum bits needed to represent value
int bitsNeeded = first_bit_high(maxValue) + 1;Priority Queue
// Find lowest priority (highest bit = lowest priority)
int lowestPriority = first_bit_high(priorityMask);Quadtree Level
// Determine quadtree level from cell size
int level = maxLevel - first_bit_high(cellSize);Zero Input
When x is 0, the result is implementation-defined (typically -1). Always check for zero if it's a possibility.
Signed vs Unsigned
For signed integers, the function finds the highest bit that differs from the sign bit. For positive numbers, this is the highest 1 bit. For negative numbers, behavior may vary.
Compiled Output
When compiled to GLSL:
findMSB(x)
When compiled to HLSL:
firstbithigh(x)
When compiled to Metal:
31 - clz(x) // 31 minus count leading zeros
When compiled to SPIR-V:
Uses GLSLstd450FindSMsb (signed) or GLSLstd450FindUMsb (unsigned).
See Also
- first_bit_low - Find lowest set bit
- count_bits - Count set bits
- log2 - Floating-point log base 2