Intrinsics2 min read

first_bit_high

Finds the position of the highest set bit.

Reading Time
2 min
Word Count
183
Sections
13
Try It Live

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 Playground

Live Demo

The first_bit_high function returns the bit position of the highest (most significant) bit that is set to 1.

Signature

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

Parameters

ParameterTypeDescription
xint or uintThe 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

bwsl
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

bwsl
// Integer log base 2
int log2Value = first_bit_high(x);

Mipmap Levels

bwsl
// Number of mip levels for texture
int mips = first_bit_high(max(width, height)) + 1;

Power of 2 Rounding

bwsl
// Round up to next power of 2
int highBit = first_bit_high(x - 1) + 1;
int nextPow2 = 1 << highBit;

Bit Width

bwsl
// Minimum bits needed to represent value
int bitsNeeded = first_bit_high(maxValue) + 1;

Priority Queue

bwsl
// Find lowest priority (highest bit = lowest priority)
int lowestPriority = first_bit_high(priorityMask);

Quadtree Level

bwsl
// 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:

glsl
findMSB(x)

When compiled to HLSL:

hlsl
firstbithigh(x)

When compiled to Metal:

metal
31 - clz(x)  // 31 minus count leading zeros

When compiled to SPIR-V:

Uses GLSLstd450FindSMsb (signed) or GLSLstd450FindUMsb (unsigned).

See Also