Parsing data and displaying hex

I am sort of a novice to Ruby so I will just start out with a
simplified example what I want to do. I have an array with two bytes
in it [0x03,0x9A] and depending on what the byte order of the file
(not the architecture) is want to display these bytes as 922 or 39427
(both unsigned shorts). I want to do this without reversing the index
on the array or anything goofy like that. Whats the most proper way to
do this in Ruby? I suspect my solution lies somewhere in pack... I
toyed with it briefly but decided to ask.

Ray Pendergraph wrote:

I am sort of a novice to Ruby so I will just start out with a
simplified example what I want to do. I have an array with two bytes
in it [0x03,0x9A] and depending on what the byte order of the file
(not the architecture) is want to display these bytes as 922 or 39427
(both unsigned shorts). I want to do this without reversing the index
on the array or anything goofy like that. Whats the most proper way to
do this in Ruby? I suspect my solution lies somewhere in pack... I
toyed with it briefly but decided to ask.

I don' t know if this is goofy or not, but here goes:

irb(main):005:0> a = [0x03,0x9a]
=> [3, 154]
irb(main):006:0> p (a[0]<<8)+a[1]
922
=> nil
irb(main):007:0> p (a[1]<<8)+a[0]
39427
=> nil
irb(main):008:0>

unpack is easier than it first looks...
Assuming unsigned integers:

# pack the bytes
bytes = [0x03,0x9A].pack('cc')
# unpack in big-endian
big = bytes.unpack('n')
# unpack small-endian
small = bytes.unpack('v')

I'm not sure if there's a way to use pack for this using signed
integers. I didn't see anything in the reference that offers unpacking
two bytes as signed little-endian integers. If you need signed
integers, you might have to resort to tricks.

reference for string.unpack:
http://www.rubycentral.com/ref/ref_c_string.html#unpack

hth,
Mark

ยทยทยท

On Fri, 8 Oct 2004 23:04:44 +0900, Ray Pendergraph <raymondpendergraph@yahoo.com> wrote:

I am sort of a novice to Ruby so I will just start out with a
simplified example what I want to do. I have an array with two bytes
in it [0x03,0x9A] and depending on what the byte order of the file
(not the architecture) is want to display these bytes as 922 or 39427
(both unsigned shorts). I want to do this without reversing the index
on the array or anything goofy like that. Whats the most proper way to
do this in Ruby? I suspect my solution lies somewhere in pack... I
toyed with it briefly but decided to ask.