-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhexlify.rb
More file actions
executable file
·51 lines (45 loc) · 792 Bytes
/
hexlify.rb
File metadata and controls
executable file
·51 lines (45 loc) · 792 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#!/usr/bin/env ruby
#
# usage: hexlify.rb [-de]
#
# Hexlify or dehexlify stdin.
def hexlify
offset = 0
while (str = $stdin.read(16))
out = "#{'%08x' % offset} "
out << hex_digits(str)
out << ' '
out << ascii(str)
puts out
offset += 16
end
end
def hex_digits(str)
offset = 0
out = ''
str.each_byte { | c |
out << ' ' if offset == 0
out << '%02x' % c
offset = (offset == 0 ? 1 : 0)
}
'%-40s' % out
end
def ascii(str)
out = ''
str.each_byte { | c | out << (printable?(c) ? c.chr : '.') }
out
end
def printable?(c)
c >= 32 && c < 127
end
def dehexlify
while (str = $stdin.gets)
str = str[/ .* /].gsub(/ /, '')
print str.gsub(/(..)/) { '%c' % $1.to_i(16) }
end
end
if ARGV[0] == '-de'
dehexlify
else
hexlify
end