Ruby: 4-byte array for int32

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

Or maybe TCPSocket has some method for reading int32 immediately?

+4
source share
1 answer

You can use String # unpack . The argument indicates the type of conversion. "N"used below and means "32-bit unsigned, network (byte) byte order". See Link for all parameters.

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

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

, Array, [0] .first, Fixnum.


Array # :

Array # pack

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

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

, N, " "

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

Source: https://habr.com/ru/post/1541727/


All Articles