Ruby: 4-bytes array to int32
Asked Answered
M

1

5

There are 4 bytes read from TCPSocket (actually socket returns a string and then I call .bytes to get an array). Now they need to be converted to int32 big endian.

Or may be TCPSocket has some method to read int32 immediately?

Muth answered 23/5, 2014 at 8:6 Comment(0)
E
7

You can use String#unpack. The argument indicates the type of conversion. "N" is used below and denotes "32-bit unsigned, network (big-endian) byte order". 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.


Original answer with Array#pack with transforms byte Array to binary String:

You can use 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"

# 32-bit unsigned, network (big-endian) byte order
bytes.pack('N*')
Elielia answered 23/5, 2014 at 8:37 Comment(6)
Since he starts with a String from TCPSocket, would String#unpack not be slightly more suitable? For example "\x00\x00\x00\xFF".unpack("N*")" => [255]. Array#pack also seems to still yield a binary string not a number?Remembrance
@p11y: shouldn't it be str.unpack instead of str.pack ?Muth
@Muth Yes you probably want to use that, see my comment earlier.Remembrance
@Daniël Knippers: I just do not understand the answer completely. There is a reference to unpack at the beginning, but all the examples use pack which produces a string rather than integer. I am a bit cautious to edit answer by myself as I could miss some hidden sense in there.Muth
@Muth I edited the answer to include working examples for String#unpack, I put his old answer below it for reference which transforms an Array of bytes into a binary String.Remembrance
@DaniëlKnippers thanks for the edit and sorry for the confusion. I am on my mobile device right now and simply messed up the edit.Elielia

© 2022 - 2024 — McMap. All rights reserved.