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?
The standard tools for byte wrangling in Ruby (and Perl and Python and …) are
packandunpack. Ruby’spackis inArray. You have a length that should be two bytes long and in network byte order, that sounds like a job for thenformat specifier:So if the length is in
length, you’d get your two bytes thusly:If you need to do the opposite, have a look at
String#unpack: