bit
The LuaJIT BitOp library, unchanged by the client: bitwise operations on 32-bit integers, since Lua 5.1 has no bitwise operators.
At a glance
Every operand is normalized to a signed 32-bit integer (modulo 2^32, fractions rounded to the nearest, ties to even) and every result is signed: bit.band(0xffffffff, -1) is -1. Numeric strings are accepted. Shift and rotate counts are taken modulo 32. Use bit.tohex or x % 2^32 to show a value as unsigned.
All functions raise bad argument #1 to 'band' (number expected, got string) (with the right name and position) for a value that is not a number.
Functions
bit.band(x, ...): number
bit.band(x: number, ...: number): number
Returns: the bitwise AND of all arguments.
local flags = 0x13
print(bit.band(flags, 0x02) ~= 0)
bit.bor(x, ...): number
bit.bor(x: number, ...: number): number
Returns: the bitwise OR of all arguments.
bit.bxor(x, ...): number
bit.bxor(x: number, ...: number): number
Returns: the bitwise XOR of all arguments.
bit.bnot(x): number
bit.bnot(x: number): number
Returns: x with every bit inverted.
bit.lshift(x, n): number
bit.lshift(x: number, n: number): number
Returns: x shifted left by n bits, zeros shifted in.
bit.rshift(x, n): number
bit.rshift(x: number, n: number): number
Returns: x shifted right by n bits, zeros shifted in.
bit.arshift(x, n): number
bit.arshift(x: number, n: number): number
Returns: x shifted right by n bits, the sign bit replicated.
print(bit.arshift(-256, 4), bit.rshift(-256, 4))
bit.rol(x, n): number
bit.rol(x: number, n: number): number
Returns: x rotated left by n bits.
bit.ror(x, n): number
bit.ror(x: number, n: number): number
Returns: x rotated right by n bits.
bit.bswap(x): number
bit.bswap(x: number): number
Returns: x with its 4 bytes in reverse order (endianness conversion).
print(bit.tohex(bit.bswap(0x12345678)))
bit.tobit(x): number
bit.tobit(x: number): number
Returns: x normalized to a signed 32-bit integer.
print(bit.tobit(0xffffffff), bit.tobit(2^32 + 5), bit.tobit(2.5))
bit.tohex(x, n): string
bit.tohex(x: number, n?: number = 8): string
Returns: the hexadecimal string, without 0x.
print(bit.tohex(255), bit.tohex(255, -4), bit.tohex(0x1234, 2))
Complete example
Pack a color in one integer and read the channels back.
local function pack(r, g, b, a)
return bit.bor(bit.lshift(a, 24), bit.lshift(r, 16), bit.lshift(g, 8), b)
end
local function unpack_color(value)
return bit.band(bit.rshift(value, 16), 255),
bit.band(bit.rshift(value, 8), 255),
bit.band(value, 255),
bit.band(bit.rshift(value, 24), 255)
end
local packed = pack(10, 20, 30, 255)
print(bit.tohex(packed), packed, packed % 2^32)
print(unpack_color(packed))