What Does findLSB Return in GLSL?
In the OpenGL Shading Language (GLSL), the built-in function
findLSB returns the zero-based index of the least
significant bit set to 1 in an integer, or -1 if no bits
are set. This article explains the exact return values of
findLSB, how it handles different data types, and edge
cases such as zero and negative integers.
Return Values of
findLSB
The findLSB function scans the binary representation of
an integer from right to left (least significant to most significant
bit) and determines the position of the first set bit
(1):
- When a set bit is found: It returns an integer
ranging from
0to31, where0represents the least significant bit (\(2^0\)) and31represents the most significant bit in a standard 32-bit integer. - When no set bits are found: If the input value is
0,findLSBreturns-1.
Supported Signatures and Types
The function is overloaded to accept both signed and unsigned 32-bit integers, as well as their vector equivalents:
genIType findLSB(genIType value)genIType findLSB(genUType value)
In GLSL, genIType covers int,
ivec2, ivec3, and ivec4, while
genUType covers uint, uvec2,
uvec3, and uvec4. When applied to vector
types, the operation executes per-component, returning a vector of
signed integers (ivec) containing the results for each
corresponding component.
Examples
findLSB(1)returns0(binary...00000001, bit 0 is set).findLSB(16)returns4(binary...00010000, bit 4 is set).findLSB(10)returns1(binary...00001010, lowest set bit is bit 1).findLSB(0)returns-1(no bits are set).findLSB(-4)returns2(in two's complement,-4is...11111100, lowest set bit is bit 2).findLSB(uvec2(0u, 8u))returnsivec2(-1, 3).