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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With