Hex Dump

lua-users home
wiki

Dump a string in the following format:
   00F52960  2F 4C 5B E1 4D C4 BE 94  95 E6 C9 3F 92 C4 53 3B  /L[.M......?..S;
   00F52970  75 44 CD 14 BE 9A AF 3F  DE 67 BA 94 39 45 AD 1E  uD.....?.g...E..
   00F52980  B1 CF 94 3F 24 23 C6 E2  BC BA 3B 31 61 8B 7A 3F  ...?$#....;.a.z?
   00F52990  61 55 59 C1 7E B1 53 7C  12 BB 5F 3F D7 EE 2F 8D  aUY.~.S|.._?../.
   00F529A0  06 BE 92 85 15 FB 44 3F  24 3F A5 E9 39 A5 27 EA  ......D?$?....'.
   00F529B0  7F A8 2A 3F 7D AC A1 E4  BC 64 7C 46 D0 DD 55 3E  ..*?}....d|F..U>
   00F529C0  63 7B 06 CC 23 54 77 83  FF 91 81 3D 91 FA 3A 19  c{..#Tw....=..:.
   00F529D0  7A 63 25 43 31 C0 AC 3C  21 89 D1                 zc%C...<!..     

I came here looking for Lua code to do that (because I'm lazy), but there was nothing here. So here ya go.

   function hex_dump(buf)
      for i=1,math.ceil(#buf/16) * 16 do
         if (i-1) % 16 == 0 then io.write(string.format('%08X  ', i-1)) end
         io.write( i > #buf and '   ' or string.format('%02X ', buf:byte(i)) )
         if i %  8 == 0 then io.write(' ') end
         if i % 16 == 0 then io.write( buf:sub(i-16+1, i):gsub('%c','.'), '\n' ) end
      end
   end

See test/xd.lua in the source distribution. --lhf

Ahhh.... thanks. Wish I'd seen that earlier. :) I'll include that version here as well. -- ewt

As Luiz points out, there's a hex dump in the Lua distro. Here's that implementation modified to operate on a string rather than a file:

   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

I'll leave mine here as well, because it separates DWORDs by a space (my preference), which would be somewhat messy to patch into the distro version (because it iterates with gsub).

Variation that accepts an optional byte range:

   -- [first] begin dump at 16 byte-aligned offset containing 'first' byte
   -- [last] end dump at 16 byte-aligned offset containing 'last' byte
   function hex_dump(buf,first,last)
      local function align(n) return math.ceil(n/16) * 16 end
      for i=(align((first or 1)-16)+1),align(math.min(last or #buf,#buf)) do
         if (i-1) % 16 == 0 then io.write(string.format('%08X  ', i-1)) end
         io.write( i > #buf and '   ' or string.format('%02X ', buf:byte(i)) )
         if i %  8 == 0 then io.write(' ') end
         if i % 16 == 0 then io.write( buf:sub(i-16+1, i):gsub('%c','.'), '\n' ) end
         end
      end


RecentChanges · preferences
edit · history
Last edited May 25, 2017 6:00 pm GMT (diff)