Intrinsics1 min read

bitfield_insert

Inserts a contiguous range of bits into an integer.

Reading Time
1 min
Word Count
113
Sections
7
Try It Live

Test bitfield_insert in a live shader

Open the playground, start from a visual preset, and wire bitfield_insert into the fragment stage to see how it behaves with real values.

Open Playground

The bitfield_insert function replaces a bit field in base with the low bits bits from insert.

Live Demo

Signature

bwsl
bitfield_insert :: (int base, int insert, int offset, int bits) -> int
bitfield_insert :: (uint base, uint insert, int offset, int bits) -> uint

Parameters

ParameterTypeDescription
baseint or uintOriginal integer
insertint or uintSource value for the inserted field
offsetintIndex of the least-significant bit to replace
bitsintNumber of bits to replace

Return Value

Returns base with the selected bit field replaced.

Example

bwsl
uint packed = 0u;
uint alpha = 255u;
packed = bitfield_insert(packed, alpha, 24, 8);

Compiled Output

When compiled to GLSL:

glsl
bitfieldInsert(base, insert, offset, bits)

When compiled to HLSL:

hlsl
// lowered to shifts, masks, and bitwise OR

When compiled to Metal:

metal
insert_bits(base, insert, offset, bits)

See Also