0

In Ruby 1.9.3, you can do

    "\x00\x01".unpack 'S' #=> 1 * 256 + 0 = 256, my machine use little endian by default
    "\x00\x01".unpack 'S>' #=> 0 * 256 + 1 = 1

But Ruby 1.8.7 doesn't have the ">" "<" annotation. So in 1.8.7, what is the best way to do unpack with big endian?

2 Answers2

0
str = "\x00\x01"
puts str.unpack 'S'

p str.reverse
puts str.reverse.unpack 'S'


--output:--
256
"\001\000"
1
7stud
  • 46,922
  • 14
  • 101
  • 127
0

You can use n for network (big) endian 2 byte values (N for 4 byte ints) and v for little endian 2 byte integers (V for 4 bytes). See the docs.

"\x00\x01".unpack 'n'
# => [1] 
"\x00\x01".unpack 'v'
# => [256]

You really should look into upgrading your Ruby version if possible.

matt
  • 78,533
  • 8
  • 163
  • 197