Search code examples
rubyutf-8

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.


Solution

  • Try using double quotes:

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

    Then do as sepp2k suggested.