示例工程 11-formatting-and-bytes
11-formatting-and-bytes/03-pack-header/main.lua
-- @runtimes lua54
--- 演示:string.pack/unpack 读写二进制头。
local M = {}
--- @return table { packed_hex = string, magic = string, version = integer }
function M.run(log)
log = log or print
local packed = string.pack(">I2B", 0x4c46, 3)
local magic, version = string.unpack(">I2B", packed)
local hex = packed:gsub(".", function(char)
return ("%02x"):format(char:byte())
end)
log(("packed=%s"):format(hex))
log(("magic=0x%x version=%d"):format(magic, version))
return { packed_hex = hex, magic = magic, version = version }
end
if not ... then
M.run()
end
return M