Working with Binary in Ruby

This post is mainly for my own infor­ma­tion, but hope­fully some­one else will find it use­ful as well. I was strug­gling a lit­tle to find solid infor­ma­tion on how to han­dle binary files in Ruby. I appre­ci­ate that a String can dou­ble as a binary data buffer, and actu­ally depend on that quite a bit. In order to make some­thing “use­ful” that helped me learn I cre­ated a sim­ple ver­sion of the pop­u­lar tool xxd. The code can be found below.

* Note: This is most def­fi­nately pro­to­type code that needs to be refined. I’m also of the opin­ion that sev­eral parts within it are “ugly”

[source­code language=“ruby”]
#!/usr/bin/env ruby

class Hexdemo

def ini­tial­ize file­name
@filename = file­name
end

def print_file

string = File.read(@filename)

arr = data_string_to_hex_array string
print_hex_array arr

end

def data_string_to_hex_array data
tmp = []
data.each_byte { |byte| tmp.push byte.to_s(16) }
(0..(tmp.length-1)).each do |idx|
if tmp[idx].length == 1
tmp[idx] = “0” « tmp[idx] end end return tmp end def print_hex_array arr line = 0; ascii = [] print “0\t“ (0..(arr.length-1)).each do |idx| print ”][ ” if idx % 8 == 0 && idx % 16 != 0 if idx % 16 != 0 || idx == 0 print arr[idx] « ” “ if arr[idx].hex >= 32 && arr[idx].hex <= 126 ascii.push arr[idx].hex.chr else ascii.push ‘.‘ end else print “\t” « ascii.join(”) print “\n“ line += 16 ascii = [] print line.to_s « “\t“ print arr[idx] « ” “ if arr[idx].hex >= 32 && arr[idx].hex <= 126 ascii.push arr[idx].hex.chr else ascii.push ‘.‘ end end if idx == arr.length-1 remain­ing = idx-line+1 if remain­ing <= 8 print ’ ‘*3 end print ’ ‘*(16-remaining) print “\t” « ascii.join(”) end end puts ““ end end if __FILE__ == $0 h = Hexdemo.new ARGV[0] || “data.bin“ h.print_file end [/sourcecode] Below you’ll find some lovely out­put from run­ning it against Google’s logo.gif [source­code language=“html”] [email protected]:~/code/ruby$ ./hex.rb logo.gif 0 47 49 46 38 39 61 14 01 ][ 6e 00 f7 00 00 f7 f7 f7 GIF89a..n.…… 16 ff fb ff e7 e7 e7 d6 d3 ][ d6 ef eb ef ce cb ce ad .….….….… 32 14 00 de db de 18 45 ad ][ 18 49 b5 10 34 84 10 3c .…..E..I..4..< 48 94 c6 18 00 b5 b2 b5 f7 ][ f3 f7 8c 10 00 c6 be bd .….….….… 64 bd ba bd 18 4d c6 e7 e3 ][ e7 ef ef ef c6 c3 c6 f7 .…M.….…… 80 f3 ef bd be bd c6 c7 c6 ][ 08 51 08 ce cf ce 08 24 .….….Q.….$ 96 63 21 59 d6 d6 24 08 d6 ][ d7 d6 18 51 ce 9c 9e 9c c!Y..$.….Q.… 112 ef ba 00 de df de 00 65 ][ 00 d6 ae 00 63 96 ef 31 .……e.…c..1 128 65 d6 4a 7d e7 08 3c a5 ][ b5 b6 b5 9c 9a 9c 73 a2 e.J}..<.……s. 144 ef de df e7 39 71 de 6b ][ 0c 00 00 7d 08 ff cf 00 .…9q.k…}.… 160 bd b6 bd ad a6 ad a5 a2 ][ a5 e7 49 31 29 51 b5 ff .….…..I1)Q.. 176 75 63 bd 96 00 5a 8a ef ][ a5 a6 a5 10 45 b5 ad aa uc…Z.…..E… 192 ad c6 9e 00 ad ae ad f7 ][ 69 52 e7 3c 21 fd fd fd .….…iR.<!… 208 ef 59 42 63 d3 63 de 30 ][ 18 5a cb 5a b5 24 10 84 .YBc.c.0.Z.Z.$.. [/sourcecode]

Leave a Reply