Skip to content

Instantly share code, notes, and snippets.

@mdavey
Created April 28, 2015 06:52
Show Gist options
  • Save mdavey/0fd69c8f1b21cd0309a4 to your computer and use it in GitHub Desktop.
Save mdavey/0fd69c8f1b21cd0309a4 to your computer and use it in GitHub Desktop.
Dump printable strings of a hex dump (in ASCII)
local function readsection(f)
local colon = f:read(1)
if colon == nil then return nil end
if colon ~= ':' then error('section did not start with colon') end
local data = ''
while true do
local char = f:read(1)
if(char:byte() == 13) then
f:read(1) -- eat cr
return data
end
data = data .. char
end
end
local function decodecharacter(c)
if c:len() ~= 1 then error('must be single character') end
local map = {['0']=0, ['1']=1, ['2']=2, ['3']=3, ['4']=4, ['5']=5, ['6']=6,
['7']=7, ['8']=8, ['9']=9, A=10, B=11, C=12, D=13, E=14, F=15}
return map[c]
end
local function decodepair(s)
if s:len() ~= 2 then error('must be two characters in length') end
return (decodecharacter(s:sub(1,1)) * 16) + decodecharacter(s:sub(2,2))
end
local function decodesection(s)
local offset = {}
local data = {}
-- todo: last two chars = checksum(offset+data)?
for i=1, s:len(), 2 do
local pair = s:sub(i, i+1)
local value = decodepair(pair)
if i <= 8 then
table.insert(offset, value)
else
table.insert(data, value)
end
end
return offset, data
end
local function safeprintdata(data)
local chars = {}
for index, byte in ipairs(data) do
if byte >= 32 and byte <= 126 then
table.insert(chars, string.char(byte))
else
table.insert(chars, '.')
end
end
return table.concat(chars)
end
local f = io.open('P2008-V-02.08.02.hex', 'rb')
while true do
line = readsection(f)
if line == nil then break end
local offset, data = decodesection(line)
print(string.format('%-42s %s', line, safeprintdata(data)))
end
102170005B204D317878205D2020000000000000B9 [ M1xx ] .......
102180005B204D313133205D202000000000000035 [ M113 ] ......5
10219000562D30322E30382E3032202000000000F4 V-02.08.02 .....
1021A00028632920616C6973746172207379737478 (c) alistar systx
1021B000656D732C20323030312D32303132202099 ems, 2001-2012 .
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment