Search code examples
rubyarraystype-conversiontcpsocketint32

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). Now they need to be converted to int32 big endian.

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


Solution

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