tags:

views:

992

answers:

2

I'm trying to send a series of binary bytes across a socket, to meet a particular standard my company uses. No one in my company has used Ruby for this before, but in other languages, they send the data across one byte at a time, (usually with some sort of "pack" method).

I can't find anyway to create binary on the fly, or create bytes at all (the closest I can find it how you can turn a string into the bytes representing it's characters).

I know you can say something like :

@var = 0b101010101

But how would I convert a string in the form "101010101" or the resulting integer created when I do string.to_i(2) into an actual binary. If I just send the string accross a socket, won't that just send the ASCII for "0" and "1" instead of the literal characters?

Surely there is SOME way to do this natively in Ruby?

+5  A: 

Have a look at the String.unpack method. This is an example:

str = "1010"
str.unpack("cccc")
=> [49, 48, 49, 48]

This will give you integer values. There are more ways to do the conversion.

kgiannakakis
Before this post was edited, it told me about Array.pack. I don't quite understand this. If I have:@bob = ["111111111", "1000", "1111"] or whatever, and then I say:@bob.unpack(b*), it displays something like: "/377" Is that the correct binary? Isn't that only the first element of the array? How would I have it do the entire array?
Jenny
Array.pack is the opposite of String.unpack. In your example bob.pack('b*') is only packing first element of array. You probably want bob.pack('b*b*b*'). However this is something different from what you are asking for in the question.
kgiannakakis
+5  A: 

Don't know if this helps enough, but you can index the bits in an integer in ruby.

n = 0b010101

n # => 21

n = 21

n[0]  # => 1
n[1]  # => 0
n[2]  # => 1
n[3]  # => 0
n[4]  # => 1
n[5]  # => 0
Matthew Schinckel