Permalink
Browse files

borrow String.hexdump from emontis rbkb - it is the most useful metho…

…d ever written
  • Loading branch information...
1 parent b62798c commit 3d7b8d89fd1dc96bbcca7e25a5e85f2c6ea3f549 @struct committed Nov 15, 2011
Showing with 38 additions and 0 deletions.
  1. +38 −0 common/extends.rb
View
38 common/extends.rb
@@ -0,0 +1,38 @@
+## Borrowed from Eric Monti's Ruby Blackbag
+require 'stringio'
+
+class String
+ def hexdump(opt={})
+ s=self
+ out = opt[:out] || StringIO.new
+ len = (opt[:len] and opt[:len] > 0)? opt[:len] + (opt[:len] % 2) : 16
+
+ off = opt[:start_addr] || 0
+ offlen = opt[:start_len] || 8
+
+ hlen=len/2
+
+ s.scan(/(?:.|\n){1,#{len}}/) do |m|
+ out.write(off.to_s(16).rjust(offlen, "0") + ' ')
+
+ i=0
+ m.each_byte do |c|
+ out.write c.to_s(16).rjust(2,"0") + " "
+ out.write(' ') if (i+=1) == hlen
+ end
+
+ out.write(" " * (len-i) ) # pad
+ out.write(" ") if i < hlen
+
+ out.write(" |#{m.tr("\0-\37\177-\377", '.')}|\n")
+ off += m.length
+ end
+
+ out.write(off.to_s(16).rjust(offlen,'0') + "\n")
+
+ if out.class == StringIO
+ out.string
+ end
+ end
+end
+

0 comments on commit 3d7b8d8

Please sign in to comment.