Created
August 28, 2013 03:37
-
-
Save Elemecca/6361899 to your computer and use it in GitHub Desktop.
Lua function which creates a hex dump of a binary string.
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
function hex_dump (str) | |
local len = string.len( str ) | |
local dump = "" | |
local hex = "" | |
local asc = "" | |
for i = 1, len do | |
if 1 == i % 8 then | |
dump = dump .. hex .. asc .. "\n" | |
hex = string.format( "%04x: ", i - 1 ) | |
asc = "" | |
end | |
local ord = string.byte( str, i ) | |
hex = hex .. string.format( "%02x ", ord ) | |
if ord >= 32 and ord <= 126 then | |
asc = asc .. string.char( ord ) | |
else | |
asc = asc .. "." | |
end | |
end | |
return dump .. hex | |
.. string.rep( " ", 8 - len % 8 ) .. asc | |
end |
any licensing requirements to use this?
To the extent possible under law, I waive all copyright and related or neighboring rights to this work. This work is published from the United States.
Thank you!
Version from http://lua-users.org/wiki/HexDump:
function hex_dump(buf)
for byte=1, #buf, 16 do
local chunk = buf:sub(byte, byte+15)
io.write(string.format('%08X ',byte-1))
chunk:gsub('.', function (c) io.write(string.format('%02X ',string.byte(c))) end)
io.write(string.rep(' ',3*(16-#chunk)))
io.write(' ',chunk:gsub('%c','.'),"\n")
end
end
It uses io.write instead of returning a string, the function can be easily modified to buffer the output and return it whole.
There's a slight bug with this when the data is exactly aligned to 8 bytes:
0000: 77 ad a4 cc 4b a8 b5 37 w...K..7
0008: 69 02 06 13 af 37 4f a5 i....7O.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
any licensing requirements to use this?