将带有十六进制ASCII码的字符串转换为字符

时间:2021-01-23 00:09:44

I have a string containing hex code values of ASCII characters, e.g. "666f6f626172". I want to convert it to the corresponding string ("foobar").

我有一个包含ASCII字符的十六进制代码值的字符串,例如“666f6f626172”。我想将它转换为相应的字符串(“foobar”)。

This is working but ugly:

这很有效但很难看:

"666f6f626172".scan(/../).map(&:hex).map(&:chr).join # => "foobar"

Is there a better (more concise) way? Could unpack be helpful somehow?

有更好(更简洁)的方式吗?解压缩可能会有所帮助吗?

2 个解决方案

#1


38  

You can use Array#pack:

您可以使用Array#pack:

["666f6f626172"].pack('H*')
#=> "foobar"

H is the directive for a hex string (high nibble first).

H是十六进制字符串的指令(高半字节优先)。

#2


15  

Stefan has nailed it, but here's an alternative you may want to tuck away for another time and place:

斯特凡已经钉了它,但是这里有另一种选择,你可能想再收拾另一个时间和地点:

"666f6f626172".gsub(/../) { |pair| pair.hex.chr } # => "foobar"

#1


38  

You can use Array#pack:

您可以使用Array#pack:

["666f6f626172"].pack('H*')
#=> "foobar"

H is the directive for a hex string (high nibble first).

H是十六进制字符串的指令(高半字节优先)。

#2


15  

Stefan has nailed it, but here's an alternative you may want to tuck away for another time and place:

斯特凡已经钉了它,但是这里有另一种选择,你可能想再收拾另一个时间和地点:

"666f6f626172".gsub(/../) { |pair| pair.hex.chr } # => "foobar"