Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Does Ruby handle bytes/binary?

Tags:

ruby

binary

byte

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?

like image 823
J.R. Avatar asked Jul 28 '09 12:07

J.R.


2 Answers

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
like image 187
Matthew Schinckel Avatar answered Oct 07 '22 18:10

Matthew Schinckel


To make a string that has an arbitrary sequence of bytes, do something like this:

binary_string = "\xE5\xA5\xBD"

The "\x" is a special escape to encode an arbitrary byte from hex, so "\xE5" means byte 0xE5.

Then try sending that string on the socket.

like image 31
David Grayson Avatar answered Oct 07 '22 16:10

David Grayson