Skip to content

bit32

The complete bit32 library. All operations work on 32-bit unsigned integers (inputs are truncated to 32 bits; results are in 0..4294967295). This is the library for combining EConVarFlag values.

bit32.band(...), bit32.bor(...), bit32.bxor(...)

Section titled “bit32.band(...), bit32.bor(...), bit32.bxor(...)”

AND, OR, XOR over any number of arguments.

print(bit32.band(0xFF, 0x0F)) --> 15
print(bit32.bor(128, 256)) --> 384 (FCVAR_ARCHIVE | FCVAR_NOTIFY)
print(bit32.bxor(0xFF, 0xF0)) --> 15
print(bit32.bor(1, 2, 4, 8)) --> 15

Bitwise NOT.

print(bit32.bnot(0)) --> 4294967295
print(bit32.bnot(0xFF)) --> 4294967040

true when band(...) of the arguments is nonzero — the idiomatic flag check.

local flags = bit32.bor(128, 256) -- ARCHIVE | NOTIFY
print(bit32.btest(flags, 128)) --> true
print(bit32.btest(flags, 16384)) --> false (CHEAT not set)

bit32.lshift(x, disp), bit32.rshift(x, disp)

Section titled “bit32.lshift(x, disp), bit32.rshift(x, disp)”

Logical shifts (left fills with zeros; right fills with zeros — no sign extension). Negative disp shifts the other way.

print(bit32.lshift(1, 7)) --> 128
print(bit32.rshift(384, 7)) --> 3
print(bit32.lshift(1, -1)) --> 0 (acts as rshift 1)

Arithmetic right shift — fills with the sign bit, treating x as signed.

print(bit32.rshift(0x80000000, 4)) --> 134217728 (zero-filled)
print(bit32.arshift(0x80000000, 4)) --> 4026531840 (sign-filled)

bit32.lrotate(x, disp), bit32.rrotate(x, disp)

Section titled “bit32.lrotate(x, disp), bit32.rrotate(x, disp)”

Bit rotation (no bits lost).

print(bit32.lrotate(0x80000001, 1)) --> 3 (0x00000003)
print(bit32.rrotate(0x80000001, 1)) --> 3221225472 (0xC0000000)

Reads a width-bit field (default 1) starting at bit field.

print(bit32.extract(384, 7)) --> 1 (bit 7 = ARCHIVE is set)
print(bit32.extract(0xFF, 4, 4)) --> 15 (the high nibble)

Returns n with the field overwritten by v.

print(bit32.replace(0, 1, 7)) --> 128 (set bit 7)
print(bit32.replace(0xFF, 0, 4, 4)) --> 240 (clear high nibble)

Leading zero count.

print(bit32.countlz(1)) --> 31
print(bit32.countlz(0x80000000)) --> 0

Trailing zero count.

print(bit32.countrz(384)) --> 7 (384 = 0b110000000)
print(bit32.countrz(0)) --> 32

Reverses the four bytes.

print(bit32.byteswap(0x00112233)) --> 573785173 (0x33221100)