tags:

views:

475

answers:

2

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  A: 
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.

sepp2k
I need the binary values in the file not the string. This code is exactly the same as my code.
Gerhard
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.
sepp2k
+3  A: 

Try using double quotes:

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

Then do as sepp2k suggested.

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