Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does string.unpack work in Ruby?

Tags:

ruby

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).

like image 998
Ingrid Avatar asked Sep 25 '08 07:09

Ingrid


People also ask

What is unpack in Ruby?

#unpack(format) ⇒ ArrayDecodes 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 the table at the end of this entry.


1 Answers

Not 16 - it is showing 1 and 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 is hex for 97 - the value of 'a'

like image 179
Brian Avatar answered Oct 24 '22 16:10

Brian