From: Jos Backus Date: 2002-01-26T04:32:57+09:00 Subject: xxd.rb Here's a Ruby implementation of the xxd command that ships with vim. While not a complete reimplementation it does perform the most important functions, i.e. creating a text dump from a file and recreating a file from a text dump. Suggestions for improvement most welcome. #!/usr/bin/env ruby # 2002-01-22 josb # 0000000: 7f45 4c46 0101 0109 0000 0000 0000 0000 .ELF............ class Fixnum def even? self % 2 == 0 end end n = 16 pat = /^[\da-f]{7}:(( [\da-f]{4}){1,8})/ def printable(c) case c when 0..037, 0177..0377 then "." else c.chr end end revert = nil while ARGV[0] =~ /^-/ case ARGV[0] when "-r" revert = 1 end ARGV.shift end def printline(n,c,chars) line, i = "", 0 line = chars.map {|ch| i += 1; sprintf "%02x%s", ch, i.even? ? ' ' : '' } text = chars.map {|ch| printable(ch) } printf "%07x: %-40s %-#{n}s\n", c - c % n, line, text end if revert $stdout.binmode # when running under DOS/Windows while line = gets if m = pat.match(line) print m[1].split(' ').map {|h| h.hex}.pack("n*") end end else File::open(ARGV.shift) {|f| c = 0 while ch = f.getc chars = [] if c % n == 0 chars << ch c += 1 printline(n, c - n, chars) if c % n == 0 end # Print remaining bytes printline(n, c, chars) unless chars.empty? } end exit -- Jos Backus _/ _/_/_/ Santa Clara, CA _/ _/ _/ _/ _/_/_/ _/ _/ _/ _/ josb@cncdsl.com _/_/ _/_/_/ use Std::Disclaimer;