Skip to content

Bit

Bit manipulation functions for working with 32-bit unsigned integers. All functions take 32-bit unsigned integers and return a signed 32-bit result.

TIP

If you need unsigned results, use Lua's built-in bit32 library instead.

bit.badd

Adds two or more integers together using bitwise addition.

lua
bit.badd(...: uint) -> int

Example

lua
print(bit.badd(10, 20))     --> 30
print(bit.badd(1, 2, 3, 4)) --> 10

bit.bsub

Subtracts two or more integers (left to right).

lua
bit.bsub(...: uint) -> int

Example

lua
print(bit.bsub(100, 30))    --> 70
print(bit.bsub(100, 20, 10)) --> 70

bit.bmul

Multiplies two or more integers together.

lua
bit.bmul(...: uint) -> int

Example

lua
print(bit.bmul(5, 10))   --> 50
print(bit.bmul(2, 3, 4)) --> 24

bit.bdiv

Divides two or more integers (left to right).

lua
bit.bdiv(...: uint) -> int

Example

lua
print(bit.bdiv(100, 10))    --> 10
print(bit.bdiv(100, 2, 5))  --> 10

bit.bswap

Inverts the endianness (byte order) of a value.

lua
bit.bswap(value: uint) -> int

Example

lua
print(bit.bswap(0x12345678)) --> 0x78563412

bit.rol

Rotates a value left by n bits.

lua
bit.rol(value: uint, n: uint) -> int
ParameterTypeDescription
valueuintThe value to rotate
nuintNumber of bits to rotate

Example

lua
print(bit.rol(1, 4)) --> 16

bit.ror

Rotates a value right by n bits.

lua
bit.ror(value: uint, n: uint) -> int
ParameterTypeDescription
valueuintThe value to rotate
nuintNumber of bits to rotate

Example

lua
print(bit.ror(16, 4)) --> 1

bit.tobit

Converts a value into the proper form for bitwise operations (normalizes to signed 32-bit integer).

lua
bit.tobit(value: uint) -> int

Example

lua
print(bit.tobit(0xFFFFFFFF)) --> -1
print(bit.tobit(42))         --> 42

bit.tohex

Converts a value to a hexadecimal string representation.

lua
bit.tohex(value: uint) -> string

Example

lua
print(bit.tohex(255))     --> "000000ff"
print(bit.tohex(0xDEAD))  --> "0000dead"