Skip to content

Instantly share code, notes, and snippets.

@dpino
Created November 2, 2015 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpino/73c08ccfe6ca074fac36 to your computer and use it in GitHub Desktop.
Save dpino/73c08ccfe6ca074fac36 to your computer and use it in GitHub Desktop.
Bitwise operator module for Lua in plain Lua
local MAX = 64
function tobit(n)
local ret = {}
for i=MAX-1,0,-1 do
if n / 2^i >= 1 then
ret[i+1] = 1
n = n % 2^i
else
ret[i+1] = 0
end
end
return ret
end
function tonum(b)
local ret = 0
for i=0,MAX-1 do
ret = ret + b[i+1] * 2^i
end
return ret
end
function lshift(n, b)
return n * 2^b
end
function rshift(n, b)
return n / 2^b
end
function band(n, m)
local ret = {}
local n, m = tobit(n), tobit(m)
for i=1,MAX do
ret[i] = (n[i] == 1 and m[i] == 1) and 1 or 0
end
return tonum(ret)
end
function bor(n, m)
local ret = {}
local n, m = tobit(n), tobit(m)
for i=1,MAX do
ret[i] = (n[i] == 1 or m[i] == 1) and 1 or 0
end
return tonum(ret)
end
assert(tonum(tobit(15)) == 15)
assert(lshift(0x1, 1) == 0x2)
assert(rshift(0x2, 1) == 0x1)
assert(band(0xF, 0x1) == 0x1)
assert(band(0xF, 0x2) == 0x2)
assert(band(0x10,0xF) == 0x0)
assert(bor(0x1, 0x2) == 0x3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment