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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22957688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:26:23  来源:igfitidea点击:

Convert string with hex ASCII codes to characters

rubyascii

提问by undur_gongor

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 unpackbe helpful somehow?

有没有更好(更简洁)的方法?可以unpack以某种方式有所帮助吗?

回答by Stefan

You can use Array#pack:

您可以使用Array#pack

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

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

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

回答by Cary Swoveland

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

Stefan 已经搞定了,但这里有一个替代方案,你可能想在另一个时间和地点藏起来:

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