Ruby - How to represent message length as 2 binary bytes
binary, byte, ruby, sockets
Solution
The standard tools for byte wrangling in Ruby (and Perl and Python and ...) are `pack` and `unpack`. Ruby's `pack` is in `Array`. You have a length that should be two bytes long and in network byte order, that sounds like a job for the `n` format specifier:
n | Integer | 16-bit unsigned, network (big-endian) byte order
So if the length is in `length`, you'd get your two bytes thusly:
two_bytes = [ length ].pack('n')
If you need to do the opposite, have a look at `String#unpack`:
length = two_bytes.unpack('n').first
Problem
I'm using Ruby and I'm communicating with a network endpoint that requires the formatting of a 'header' prior to sending the message itself. The first field in the header must be the message length which is defined as a 2 binary byte message length in network byte order. For example, my message is 1024 in length. How do I represent 1024 as binary two-bytes?