Created
May 9, 2011 06:10
-
-
Save takumakei/962132 to your computer and use it in GitHub Desktop.
print hex dump of a string
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
# 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