红宝石 - 如何重新present消息长度为2个二进制字节 [英] Ruby - How to represent message length as 2 binary bytes

查看:109
本文介绍了红宝石 - 如何重新present消息长度为2个二进制字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Ruby和我有一个需要'头'的格式之前,发送消息本身就是一个网络端点通信。

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.

标头中的第一个字段必须是其被定义为在网络字节顺序的2个二进制字节消息长度的消息长度。

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.

例如,我的消息长度为1024。我该如何重新present 1024二进制两字节?

For example, my message is 1024 in length. How do I represent 1024 as binary two-bytes?

推荐答案

标准工具字节在Ruby中争吵(和Per​​l和Python和...)是解压。 Ruby的 阵列 。你有一个长度,应该是两个字节长,网络字节顺序,这听起来像一个作业 N 格式说明:

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 |整数| 16位无符号,网络(大尾数)字节顺序

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')

如果你需要做的正好相反,看看<一个href=\"http://ruby-doc.org/core-1.9.3/String.html#method-i-unpack\"><$c$c>String#unpack:

If you need to do the opposite, have a look at String#unpack:

length = two_bytes.unpack('n').first

这篇关于红宝石 - 如何重新present消息长度为2个二进制字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆