Skip to content

Instantly share code, notes, and snippets.

@Elemecca
Created August 28, 2013 03:37
Show Gist options
  • Save Elemecca/6361899 to your computer and use it in GitHub Desktop.
Save Elemecca/6361899 to your computer and use it in GitHub Desktop.
Lua function which creates a hex dump of a binary string.
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
@Sainan
Copy link

Sainan commented Jan 2, 2024

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