Skip to content

Instantly share code, notes, and snippets.

@xebecnan
Created August 25, 2022 03:09
Show Gist options
  • Save xebecnan/7fdb4b7eaf0206e8e66271abfd8a1f37 to your computer and use it in GitHub Desktop.
Save xebecnan/7fdb4b7eaf0206e8e66271abfd8a1f37 to your computer and use it in GitHub Desktop.
bit array implemented in Lua
local M = {}
local BITS_PER_BYTE = 8
local BYTES_PER_INT = string.packsize('j')
local BITS_PER_INT = BITS_PER_BYTE * BYTES_PER_INT
function M.get_bit(h, i)
local index = i // BITS_PER_INT
local v = h[index]
if not v then
return false
end
local mask = 1 << (i % BITS_PER_INT)
return v & mask ~= 0
end
function M.set_bit(h, i, b)
local index = i // BITS_PER_INT
local mask = 1 << (i % BITS_PER_INT)
local v = h[index]
if not v then
if b then
h[index] = mask
end
return
end
if b then
v = v | mask
else
v = v & ~mask
end
h[index] = v ~= 0 and v or nil
end
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment