Module:CommonData/Bit

-- -- Module that provides an interface with Lua bit --

local function bit_band(a, b)   local result = 0 local bitval = 1 while a > 0 and b > 0 do     if a % 2 == 1 and b % 2 == 1 then result = result + bitval end bitval = bitval * 2 a = math.floor(a/2) b = math.floor(b/2) end return result end

-- bor, bxor, band = 1, 3, 4 local function _bit(oper, a, b)  local result, bitval, s = 0, 2147483648 --2^31 repeat s,a,b = a + b + bitval, a % bitval, b % bitval result = result + bitval * oper % (s-a-b) bitval = bitval / 2 until bitval < 1 return result end

local p = {}

function p.IsFlag( frame ) local args = frame.args local value,flags = tonumber(args[1]) or 0, tonumber(args[2]) or 0 --return bit_band(value, flags) == flags and tostring(flags) or "" return _bit(4, value, flags) == flags and tostring(flags) or "" end

function p.AnyFlag( frame ) local args = frame.args --local flags = bit_band(tonumber(args[1]) or 0, tonumber(args[2]) or 0) local flags = _bit(4, tonumber(args[1]) or 0, tonumber(args[2]) or 0) return flags == 0 and "" or tostring(flags) end

function p.bor( frame ) local args = frame.args return tostring(_bit(1, tonumber(args[1]) or 0, tonumber(args[2]) or 0)) end

function p.bxor( frame ) local args = frame.args return tostring(_bit(3, tonumber(args[1]) or 0, tonumber(args[2]) or 0)) end

function p.band( frame ) local args = frame.args return tostring(_bit(4, tonumber(args[1]) or 0, tonumber(args[2]) or 0)) end

function p.bnop( frame ) --local args = frame.args --return tostring((tonumber(args[1]) or 0) .. (tonumber(args[2]) or 0)) end

return p