local mybit = { } mybit.rshift = function(value, bit) return math.floor(value / (2 ^ bit)) end mybit.lshift = function(value, bit) return value * (2 ^ bit) end mybit.band = function(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 a = math.floor(a / 2) b = math.floor(b / 2) bitval = bitval * 2 end return result end mybit.bor = function(a, b) local result = 0 local shift = 1 while a > 0 or b > 0 do local r1 = a % 2 local r2 = b % 2 if r1 == 1 or r2 == 1 then result = result + shift end a = math.floor(a / 2) b = math.floor(b / 2) shift = shift * 2 end return result end mybit.bytes = function(value) local bytes = { } if value == 0 then return { 0 } end while value > 0 do bytes[#bytes + 1] = value % 256 value = math.floor(value / 256) end return bytes end mybit.nbytes = function(value, num) local bytes = { } num = num or 1 for i = 1, num do bytes[i] = value % 256 value = math.floor(value / 256) end return bytes end mybit.align16bytes = function(value) return math.ceil(value / 16) * 16 end mybit.hexval = function(word) local con = string.sub(word, 3) con = tonumber(con, 16) return con end mybit.bitval = function(b) local dig = b:sub(3) local len = #dig local result = 0 for i = 1, len do local b = dig:sub(i, i) result = result + b * (2 ^ (len - i)) end return result end mybit.tobits = function(num, size) local bits = { } while true do local b = mybit.band(num, 1) num = mybit.rshift(num, 1) table.insert(bits, 1, tostring(b)) if num == 0 then break end end if #bits < size then for i = 1, size - #bits do table.insert(bits, 1, "0") end end return table.concat(bits) end return mybit