Skip to content

Instantly share code, notes, and snippets.

@takumakei
Created May 9, 2011 06:10
Show Gist options
  • Save takumakei/962132 to your computer and use it in GitHub Desktop.
Save takumakei/962132 to your computer and use it in GitHub Desktop.
print hex dump of a string
# hex_dump.rb
# print hex dump of a string
module HexDump
module_function
def hex_dump(str)
cs = str.unpack 'C*'
puts "[#{cs.size} bytes]"
addr = 0
loop do
cs16 = cs.shift 16
break if cs16.empty?
hexs = cs16.map{|x| "%02x" % x}.join ' '
chrs = cs16.map{|x| (31 < x && x < 127) ? x.chr : '.'}.join
puts "%08x %-47s %s" % [addr, hexs, chrs]
addr += 16
end
end
end
if $0 == __FILE__
HexDump.hex_dump File.read __FILE__
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment