Module: Hexdump
Overview
Provides the Hexdump.dump method and can add hexdumping to other classes by including the Hexdump module.
class AbstractData
include Hexdump
def each_byte
# ...
end
end
data = AbstractData.new
data.hexdump
Class Method Summary collapse
-
.dump(data, options = {}) {|index, hex_segment, print_segment| ... } ⇒ nil
Hexdumps the given data.
Instance Method Summary collapse
-
#hexdump(options = {}, &block) ⇒ Object
Hexdumps the object.
Class Method Details
.dump(data, options = {}) {|index, hex_segment, print_segment| ... } ⇒ nil
Hexdumps the given data.
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
# File 'lib/hexdump/hexdump.rb', line 60 def Hexdump.dump(data,={}) unless data.respond_to?(:each_byte) raise(ArgumentError,"the data to hexdump must define #each_byte") end output = .fetch(:output,STDOUT) unless output.respond_to?(:<<) raise(ArgumentError,":output must support the #<< method") end width = .fetch(:width,16) base = .fetch(:base,:hexadecimal) ascii = .fetch(:ascii,false) byte_width, byte_format = case base when :hexadecimal, :hex, 16 [2, "%.2x"] when :decimal, :dec, 10 [3, "%3.d"] when :octal, :oct, 8 [4, "0%.3o"] when :binary, :bin, 2 [8, "%.8b"] end hex_byte = lambda { |byte| if (ascii && (byte >= 0x20 && byte <= 0x7e)) byte.chr else byte_format % byte end } print_byte = lambda { |byte| if (byte >= 0x20 && byte <= 0x7e) byte.chr else '.' end } index = 0 hex_segment_width = ((width * byte_width) + (width - 1)) line_format = "%.8x %-#{hex_segment_width}s |%s|\n" data.each_byte.each_slice(width) do |bytes| hex_segment = bytes.map(&hex_byte) print_segment = bytes.map(&print_byte) if block_given? yield(index,hex_segment,print_segment) else output << sprintf( line_format, index, hex_segment.join(' '), print_segment.join ) end index += width end # flush the hexdump buffer return nil end |