Intrinsics1 min read
reverse_bits
Reverses the order of bits in an integer.
Reading Time
1 min
Word Count
156
Sections
12
Try It Live
Test reverse_bits in a live shader
Open the playground, start from a visual preset, and wire reverse_bits into the fragment stage to see how it behaves with real values.
Open PlaygroundLive Demo
The reverse_bits function returns the value with its bits in reversed order. Bit 0 becomes bit 31, bit 1 becomes bit 30, and so on.
Signature
bwsl
reverse_bits :: (int x) -> int {...}
reverse_bits :: (uint x) -> uint {...}
Parameters
| Parameter | Type | Description |
|---|---|---|
x | int or uint | The value to reverse |
Return Value
Returns x with bits in reversed order.
Example
bwsl
pipeline BitReversedFFT {
pass "Main" {
compute "Main" [64, 1, 1] {
// Bit-reversal permutation for FFT
uint index = input.global_id.x;
uint reversedIndex = reverse_bits(index) >> (32 - logN);
// Swap elements at index and reversedIndex
if (index < reversedIndex) {
float2 temp = data[index];
data[index] = data[reversedIndex];
data[reversedIndex] = temp;
}
}
}
}Common Use Cases
FFT Bit Reversal
bwsl
// Bit-reversed addressing for FFT
uint bitRev = reverse_bits(i) >> (32 - log2N);
float2 sample = inputBuffer[bitRev];Texture Coordinate Tricks
bwsl
// Create interesting patterns via bit manipulation
uint bits = uint(uv.x * 256.0);
uint reversed = reverse_bits(bits) >> 24;
float pattern = float(reversed) / 256.0;Hash Functions
bwsl
// Part of hash function
uint hash = value;
hash = reverse_bits(hash);
hash ^= hash >> 16;Fractal Patterns
bwsl
// Van der Corput sequence
uint bits = reverse_bits(sampleIndex);
float radical = float(bits) / float(0xFFFFFFFF);Data Encoding
bwsl
// Reverse bits for specific protocols
uint encoded = reverse_bits(data);Shift After Reverse
When working with values smaller than 32 bits, shift right after reversing. For an N-bit value: reverse_bits(x) >> (32 - N).
Van der Corput
Bit reversal is used to generate low-discrepancy sequences for quasi-Monte Carlo sampling.
Compiled Output
When compiled to GLSL:
glsl
bitfieldReverse(x)
When compiled to HLSL:
hlsl
reversebits(x)
When compiled to Metal:
metal
reverse_bits(x)
When compiled to SPIR-V:
Uses OpBitReverse instruction.
See Also
- count_bits - Count set bits
- first_bit_low - Find lowest set bit
- first_bit_high - Find highest set bit