Ger Cas
Ger Cas

Reputation: 2298

Write binary file from text string that represents hex bytes in Ruby

I have the following text string that represents hexadecimal bytes that should appear in file to create.

str = "001104059419632801001B237100300381010A"

I want to create a file that contains the above string in order when I open the created file with a Hex editor I see the same bytes

When I run this script

File.open("out.dat", 'w') {|f| f.write(str.unpack('H*')) }

it creates the file out.dat and when I open this file in a Hex editor contains this

5B2233303330333133313330333433303335333933343331333933363333333233383330333133303330333134323332333333373331333033303333333033303333333833313330333133303431225D

and I would like the content when I open the file in Hex editor be the same a text string

 001104059419632801001B237100300381010A

How can I do this?

I hope make sense. Thanks

Upvotes: 1

Views: 569

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You have to split the string by aligned bytes in the first place.

str.
  each_char.     # enumerator
  each_slice(2). # bytes
  map { |h, l| (h.to_i(16) * 16 + l.to_i(16)) }.
  pack('C*')

 #⇒ "\x00\x11\x04\x05\x94\x19c(\x01\x00\e#q\x000\x03\x81\x01\n"

or, even better:

str.
  scan(/../).
  map { |b| b.to_i(16) }.
  pack('C*')

Now you might dump this to the file using e.g. IO#binwrite.

Upvotes: 1

Related Questions