ruby pack unexpected results

8 views
Skip to first unread message

John Merlino

unread,
Jun 24, 2013, 12:49:22 PM6/24/13
to rubyonra...@googlegroups.com
I have two hex values and expect back the value "3007"


What pack does is take the array of hexes and formats them into a string (if ASCII representation, then ASCII character, otherwise the raw hex as string). Then I take the string of hexes and unpack them, that is, get the unsigned int representation of those bytes:
[0xBF, 0xB].pack('C*').unpack('I')[0]

So I expect back 3007, but the above produces nil.

This is what I want to achieve:

[0xBF, 0xB].reverse.inject { |s,v| s * 256 + v }
 => 3007 

But I want to use unpack instead of inject.


Colin Law

unread,
Jun 24, 2013, 3:59:25 PM6/24/13
to rubyonra...@googlegroups.com
On 24 June 2013 17:49, John Merlino <stoi...@aol.com> wrote:
> I have two hex values and expect back the value "3007"
>
>
> What pack does is take the array of hexes and formats them into a string (if
> ASCII representation, then ASCII character, otherwise the raw hex as
> string). Then I take the string of hexes and unpack them, that is, get the
> unsigned int representation of those bytes:
> [0xBF, 0xB].pack('C*').unpack('I')[0]
>
> So I expect back 3007, but the above produces nil.

Do the operation one step at a time in irb and you will see where it goes wrong.

Colin

Colin Law

unread,
Jun 24, 2013, 4:27:10 PM6/24/13
to rubyonra...@googlegroups.com
Hint: unpack('I') appears to expect four bytes.

Colin

>
> Colin
Reply all
Reply to author
Forward
0 new messages