lua-rtos-libs/libs/binascii.lua

42 lines
905 B
Lua

local M = {}
function M.hex(num, big)
return string.format(big and "%02X" or "%02x", num)
end
function M.hexlify(s, big)
local a = {}
local format = big and "%02X" or "%02x"
for i = 1, #s do
a[i] = string.format(format, s[i])
end
return a
end
function M.unhexlify(s)
if #s % 2 ~= 0 then
error('unhexlify: hexstring must contain an even number of digits')
end
local a = {}
for i = 1, #s, 2 do
local byte = tonumber(s:sub(i, i+1), 16)
if not byte then
error(string.format("unhexlify: encountered non-hexadecimal number at position %d", i))
end
a[#a + 1] = byte
end
return a
end
function M.bin(num)
local bin = ""
while num > 0 do
local rest = num % 2
bin = tostring(rest) .. bin
num = math.floor(num / 2)
end
return bin == "" and "0" or bin
end
return M