Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How to represent message length as 2 binary bytes

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?

like image 867
user1890597 Avatar asked Dec 10 '12 04:12

user1890597


1 Answers

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
like image 95
mu is too short Avatar answered Oct 05 '22 22:10

mu is too short