Last active
March 4, 2025 20:39
-
-
Save SeanPesce/4b6120c87450077588abcbec1c498681 to your computer and use it in GitHub Desktop.
Helper function to create a hex dump from a ByteArray object in a WireShark Lua dissector
This file contains hidden or 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
-- Author: Sean Pesce | |
-- References: | |
-- https://lua-users.org/wiki/HexDump | |
-- https://www.wireshark.org/docs/wsdg_html_chunked/lua_module_Tvb.html | |
function hex_dump(buf, print_addrs) | |
if print_addrs == nil then | |
print_addrs = false | |
end | |
local result = "" | |
for byte = 0, buf:len() - 1, 16 do | |
local chunk_sz = math.min(16, buf:len() - byte) | |
local chunk = buf:subset(byte, chunk_sz) | |
if print_addrs then | |
-- Print the starting address of the line | |
result = result .. string.format('%08X ', byte) | |
end | |
for i = 0, chunk:len() - 1 do | |
result = result .. string.format('%02X ', chunk:get_index(i)) | |
end | |
-- Pad the remaining space if the chunk is less than 16 bytes | |
result = result .. string.rep(' ', 3 * (16 - chunk:len())) | |
-- Print ASCII representation | |
result = result .. ' ' | |
for i = 0, chunk:len() - 1 do | |
local char = chunk:get_index(i) | |
if char >= 32 and char <= 126 then | |
result = result .. string.char(char) | |
else | |
result = result .. '.' | |
end | |
end | |
result = result .. "\n" | |
end | |
return result | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment