vvvnn
vvvnn

Reputation: 251

Ruby Write Hex String To Binary File By Keeping Hex Values

I want to generate random bytes in Ruby, but I also want to insert some constant values into specific positions of the random bytes.

random_hex_string = SecureRandom.hex (length)
random_hex_string.insert(0,"0102")
random_hex_string.insert(30*1,"36")

So I generate random hex bytes and insert my hex values there. The problem is that I have now a string not a byte array. So when I print it:

File.open("file.txt", 'w+b') do |f|
f.write(random_hex_string)

It - not surprisingly - converts the hex string into binary then writes it. So my hex values are not kept. To be more clear, when I write my hex string to the file, and then I want to see the same hex values when I hex dump the file. How can I do this?

Upvotes: 0

Views: 1587

Answers (2)

Stefan Pochmann
Stefan Pochmann

Reputation: 28596

Why ask for hex when you don't actually want hex? Just do this:

random_bytes = SecureRandom.random_bytes(length)
random_bytes.insert(0, "\x01\x02")
random_bytes.insert(15, "\x36")

Upvotes: 1

Simple Lime
Simple Lime

Reputation: 11035

You can turn it into a single element array and pack it as hex. For instance, when I run your code:

require 'securerandom'

length = 2 ** 6
random_hex_string = SecureRandom.hex (length)
random_hex_string.insert(0,"0102")
random_hex_string.insert(30*1,"36")

puts random_hex_string
File.open("file.txt", 'w+b') do |file|
  file.write([random_hex_string].pack('H*')) # see also 'h'
end

I get the output

010299e84e9e4541d08cb800462b6f36a87ff118d6291368e96e8907598a2dfd4090658fea1dab6ed460ab512ddc54522329f6b4ddd287e4302ef603ce60e85e631591

and then running

$ hexdump  file.txt 
0000000 01 02 99 e8 4e 9e 45 41 d0 8c b8 00 46 2b 6f 36
0000010 a8 7f f1 18 d6 29 13 68 e9 6e 89 07 59 8a 2d fd
0000020 40 90 65 8f ea 1d ab 6e d4 60 ab 51 2d dc 54 52
0000030 23 29 f6 b4 dd d2 87 e4 30 2e f6 03 ce 60 e8 5e
0000040 63 15 91                                       
0000043

Unless, I'm mistaken, it matches up perfectly with the output from the script.


I've never messed with Array#pack before, and haven't done much with hex, but this seems to be giving the results you require, so should be a step in the right direction at least.

Upvotes: 1

Related Questions