1

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Aleksei, thanks for helping me with this solution. Would your second solution with scan(/../) change if there are spaces between bytes in the hex string? I ask because the original string has spaces between bytes and I apply pre processing to remove them first and maybe with your solution could handle those spaces in the same step.
scan(/..(?=\s)/) should work out of the box (positive lookahead for two symbols followed by a space.) Also, if there are spaces, just use split(' ') instead of scan, it’s simpler and faster.
Excellent. Thanks so much again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.