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?

Paul
  • 25,812
  • 38
  • 124
  • 247

1 Answers1

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*')
Daniël Knippers
  • 3,049
  • 1
  • 11
  • 17
Patrick Oscity
  • 53,604
  • 17
  • 144
  • 168
  • 2
    Since he starts with a String from TCPSocket, would [String#unpack](http://www.ruby-doc.org/core-2.1.2/String.html#method-i-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? – Daniël Knippers May 23 '14 at 08:48
  • @p11y: shouldn't it be str.unpack instead of str.pack ? – Paul May 23 '14 at 09:39
  • @Paul Yes you probably want to use that, see my comment earlier. – Daniël Knippers May 23 '14 at 09:49
  • @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. – Paul May 23 '14 at 10:11
  • @Paul 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. – Daniël Knippers May 23 '14 at 10:25
  • @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. – Patrick Oscity May 23 '14 at 10:26