Skip to content

Instantly share code, notes, and snippets.

@liweitianux
Last active February 21, 2024 12:05
Show Gist options
  • Save liweitianux/e53bc7040295408d22e6d9df2e58f486 to your computer and use it in GitHub Desktop.
Save liweitianux/e53bc7040295408d22e6d9df2e58f486 to your computer and use it in GitHub Desktop.
Hexdump in Lua
-- Hexdump the input data using the same style as 'hexdump -C'.
-- Supports Lua 5.1 and above.
-- Credit: http://lua-users.org/wiki/HexDump
function hexdump(data)
if type(data) ~= "string" then
return nil, "expected string type, but given " .. type(data)
end
local pieces = {}
local i = 1
for byte = 1, #data, 16 do
local chunk = string.sub(data, byte, byte + 15)
pieces[i] = string.format("%08x ", byte - 1)
i = i + 1
local n = 0
chunk:gsub(".", function (c)
pieces[i] = string.format("%02x ", string.byte(c))
i = i + 1
n = n + 1
if n == 8 then
pieces[i] = " "
i = i + 1
end
end)
if n < 8 then
pieces[i] = " "
i = i + 1
end
pieces[i] = string.rep(" ", 3 * (16 - #chunk))
i = i + 1
pieces[i] = " |" .. chunk:gsub("[^%w%p ]", ".") .. "|\n"
i = i + 1
end
pieces[i] = string.format("%08x", #data) -- no '\n' at the end
return table.concat(pieces)
end
@liweitianux
Copy link
Author

Example:

-- Test
-- NOTE: escape sequence \ddd, where ddd is a sequence of up to three *decimal* digits.
--       (from: Lua Reference Manual: Lexical Conventions)
local data = "hello world\nyo\3\0045\02042\200\255 ho\0"
print(hexdump(data))

Output:

00000000  68 65 6c 6c 6f 20 77 6f  72 6c 64 0a 79 6f 03 04  |hello world.yo..|
00000010  35 14 34 32 c8 ff 20 68  6f 00                    |5.42.. ho.|
0000001a

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment