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
@keck-in-space
Copy link

Thank you!

@LolloDev5123
Copy link

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.

@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