CelinHC
CelinHC

Reputation: 1984

How do i write a string containing an array of integers to a file as bytes in Ruby?

How do I write (raw) a binary string array representation to a file?

#str is a String not an Array
str = "[80, 75, 3, 4, 10, 0, 0, 0, 0, 0, -74, 121, 57, 64, 0, 0, 0, 0]"

File.open('/Users/file.zip', "wb") do |file|
   file.write(str)
end

The code above does not work. How can I to fix it?

Upvotes: 4

Views: 7526

Answers (5)

SnakE
SnakE

Reputation: 2571

I wonder why nobody mentioned string escapes. This works:

str = "\x50\x4B\x03\x04\x0A\0\0\0\0\0\xB6\x79\x39\x40\0\0\0\0"    
File.open('file.zip', "wb") { |file| file.write(str) }

Unfortunately there are no decimal escapes so you'll have to convert your numbers either to hexadecimal or to octal.

Upvotes: 0

fschulze
fschulze

Reputation: 13

Array#pack and String#unpack convert to binary strings and back. Use IO#write and IO#read for these strings.

Upvotes: 0

Alex D
Alex D

Reputation: 30445

Most of the answers here assume you are using an Array, not a String as you stated (and as your example shows). This should work with the String you showed in the example:

File.open('/Users/file.zip', "wb") { |f| f.write(JSON.parse(str).pack('C*')) }

Just make sure to require 'json'.

Upvotes: 7

CelinHC
CelinHC

Reputation: 1984

It works, but i thought it was too dirty

str = "[80, 75, 3, 4, 10, 0, 0, 0, 0, 0, -74, 121, 57, 64, 0, 0, 0, 0]"
int_array = str.gsub('[', '').gsub(']', '').split(', ').collect{|i| i.to_i}
File.open('/Users/file.zip', "wb") do |file|
   file.write(int_array.pack('C*'))
end

Upvotes: 0

Reactormonk
Reactormonk

Reputation: 21700

Are you sure you want

str = "[80, 75, 3, 4, 10, 0, 0, 0, 0, 0, -74, 121, 57, 64, 0, 0, 0, 0]"

and not

str = [80, 75, 3, 4, 10, 0, 0, 0, 0, 0, -74, 121, 57, 64, 0, 0, 0, 0]

About writing: #write calls #to_s which converts the array to its string represenation, which isn't what you want. To control that conversion, use Array#pack. Try file.write(str.pack('C*')).

Upvotes: 0

Related Questions