Gerhard
Gerhard

Reputation: 7051

Ruby: How to convert a string to binary and write it to file

The data is a UTF-8 string:

data = 'BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08'

I have tried File.open("data.bz2", "wb").write(data.unpack('a*')) with all kinds of variations for unpack put have had no success. I just get the string in the file not the UTF-8 encoded binary data in the string.

Upvotes: 5

Views: 9837

Answers (4)

Charles Jan
Charles Jan

Reputation: 11

That should work too:

data = "BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03"
    
# write to file
File.binwrite("path/to/file", data)
    
# read from file
File.binread("path/to/file") == data

Upvotes: 1

Ulysse BN
Ulysse BN

Reputation: 11386

A more generic answer for people coming here from the internet:

data = "BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03"

# write to file
File.write("path/to/file", data, mode: "wb") # wb: write binary

# read from file
File.read("path/to/file", mode: "rb") == data # rb: read binary

Upvotes: 1

sepp2k
sepp2k

Reputation: 370102

data = "BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08"

File.open("data.bz2", "wb") do |f|
  f.write(data)
end

write takes a string as an argument and you have a string. There is no need to unpack that string first. You use Array#pack to convert an array of e.g. numbers into a binary string which you can then write to a file. If you already have a string, you don't need to pack. You use unpack to convert such a binary string back to an array after reading it from a file (or wherever).

Also note that when using File.open without a block and without saving the File object like File.open(arguments).some_method, you're leaking a file handle.

Upvotes: 12

kgiannakakis
kgiannakakis

Reputation: 104168

Try using double quotes:

data = "BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03"

Then do as sepp2k suggested.

Upvotes: 4

Related Questions