简体   繁体   English

Ruby:int32的4字节数组

[英]Ruby: 4-bytes array to int32

There are 4 bytes read from TCPSocket (actually socket returns a string and then I call .bytes to get an array). TCPSocket读取4个字节(实际上socket返回一个字符串,然后我调用.bytes来获取一个数组)。 Now they need to be converted to int32 big endian. 现在他们需要转换为int32 big endian。

Or may be TCPSocket has some method to read int32 immediately? 或者可能TCPSocket有一些方法立即读取int32?

You can use String#unpack . 您可以使用String#unpack The argument indicates the type of conversion. 参数表示转换的类型。 "N" is used below and denotes "32-bit unsigned, network (big-endian) byte order". 下面使用"N"表示“32位无符号,网络(大端)字节顺序”。 See the link for all options. 请参阅所有选项的链接。

"\x00\x00\x00\x01".unpack("N")
# => [1]

"\x00\x00\x00\xFF".unpack("N")
# => [255]

Note the result is an Array , so apply [0] or .first to obtain the Fixnum . 注意结果是一个Array ,所以应用[0].first来获取Fixnum


Original answer with Array#pack with transforms byte Array to binary String: Array#pack的原始答案,包含转换字节数组到二进制字符串:

You can use Array#pack 您可以使用Array#pack

# unsigned 32-bit integer (big endian)
bytes.pack('L>*')

# signed 32-bit integer (big endian)
bytes.pack('l>*')

Maybe you will find the N directive useful, which stands for "Network byte order" 也许你会发现N指令很有用,它代表“网络字节顺序”

# 32-bit unsigned, network (big-endian) byte order
bytes.pack('N*')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM