Todd Benson
11/7/2007 1:32:00 AM
On 11/6/07, Collin VanDyck <gluedtomyseat@gmail.com> wrote:
> Hello -- I'm trying to write out specific byte sequences over the
> wire / to a file / etc. Let's say for example that I wanted to write
> out
>
> 99 111 108 108 105 110
>
> as a simple, six byte sequence to a file. In Java, I might use the
> byte primitive, but it seems that in Ruby you have Fixnum and then a
> Float for fractions. If I simply create a Fixnum using the 99
> literal, I think that that will create more than an 8-bit sequence
> when I write out to the file.
>
> Any ideas on how to do this?
String objects are arrays of bytes, so you could simply do...
num_string = "99 111 108 108 105 110"
byte_string = num_string.split.map! {|word| word.to_i.chr}.join
# Now, to illustrate...
byte_string.class
# gives String
byte[0]
# gives 99, the base 10 representation of 1100011
# note that each byte can store numbers up to 255
puts byte_string
# gives collin
If you want to store the 1's and 0's as a text string, you can use the
Integer#to_s(2) method.
hth,
Todd