Last active
February 21, 2024 12:05
-
-
Save liweitianux/e53bc7040295408d22e6d9df2e58f486 to your computer and use it in GitHub Desktop.
Hexdump in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example:
Output: