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 开发者_StackOverflow社区the string.
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.
Try using double quotes:
data = "BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03"
Then do as sepp2k suggested.
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
精彩评论