Ruby: How to convert 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 tried File.open("data.bz2", "wb").write(data.unpack('a*'))

with all unpacking options that weren't successful. I am just getting the string in the file, not the UTF-8 encoded binary data in the string.

+2


source to share


2 answers


Try using double quotes:

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

      



Then do as sepp2k suggested.

+3


source


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 this line first. You use Array#pack

to convert an array eg. numbers to a binary string, which you can then write to a file. If you already have a string, you don't need to box. You use unpack to convert such a binary string back to an array after reading from a file (or elsewhere).



Also note that when used File.open

without a block and without storing a File object such as File.open(arguments).some_method

, you are skipping the file descriptor.

+7


source







All Articles