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?
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?
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*')
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 String#unpack
, I put his old answer below it for reference which transforms an Array of bytes into a binary String. –
Remembrance © 2022 - 2024 — McMap. All rights reserved.
"\x00\x00\x00\xFF".unpack("N*")"
=>[255]
. Array#pack also seems to still yield a binary string not a number? – Remembrance