string.unpack如何在Ruby中工作?

时间:2020-03-06 14:42:25  来源:igfitidea点击:

有人可以解释为什么接下来的解压缩结果是如何计算的吗?

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

在二进制中," a" = 01100001. 我不确定" h2"如何变为16(0001 0000)或者" H2"如何变为61(0011 1101)。

解决方案

查看关于解压缩的Ruby编程参考。这是一个片段:

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.

以及我们示例中的相关字符:

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

chara的十六进制代码为61.

模板" h2"是一个十六进制字符串(低半字节在前)," H2"与高半字节在前一样。

另请参见perl文档。

不是16,它显示1,然后显示6. h给出每个半字节的十六进制值,因此我们将得到0110(6),然后是0001(1),具体取决于我们要查看的是高位还是低位。首先使用高半字节,我们将得到61,即97的十六进制值,即" a"的值