tags:

views:

1835

answers:

3

Can someone explain why how the result for the following unpack is computed?

"aaa".unpack('h2H2')               #=> ["16", "61"]

In binary, 'a' = 0110 0001. I'm not sure how the 'h2' can become 16 (0001 0000) or 'H2' can become 61 (0011 1101).

+2  A: 

Check out the Programming Ruby reference on unpack. Here's a snippet:

Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in Table 22.8 on page 379. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (*'') will use up all remaining elements. The directives sSiIlL may each be followed by an underscore (_'') to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. See also Array#pack on page 286.

And the relevant characters from your example:

H Extract hex nibbles from each character (most significant first).

h Extract hex nibbles from each character (least significant first).

Chris Bunch
+1  A: 

The hex code of char a is 61.

Template h2 is a hex string (low nybble first), H2 is the same with high nibble first.

Also see the perl documentation.

Bruno De Fraine
+3  A: 

Not 16 - 1 then 6. h is giving the hex value of each nibble, so you get 0110 (6), then 0001 (1), depending on whether its the high or low bit you're looking at. Use the high nibble first and you get 61, which in hex for 91 - the value of 'a'

Brian