5

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.

4 Answers 4

12
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.

Sign up to request clarification or add additional context in comments.

2 Comments

I need the binary values in the file not the string. This code is exactly the same as my code.
You seem to think that a file containing the string "\x01\x02" is different from a file containing the byte 1 followed by the byte 2. This is not the case. If you simply write your string to the file, it will do what you want.
4

Try using double quotes:

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

Then do as sepp2k suggested.

2 Comments

Ahrg, I totally missed the fact that his string was single quoted. +1
Thanks. I solved it my self when I read the comment from sepp2k. The devil is in the details.
1

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

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.