将十六进制ASCII码的字符串转换为字符 [英] Convert string with hex ASCII codes to characters
本文介绍了将十六进制ASCII码的字符串转换为字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串,其中包含ASCII字符的十六进制代码值,例如"666f6f626172"
.我想将其转换为相应的字符串("foobar"
).
I have a string containing hex code values of ASCII characters, e.g. "666f6f626172"
. I want to convert it to the corresponding string ("foobar"
).
这是可行的,但是很丑:
This is working but ugly:
"666f6f626172".scan(/../).map(&:hex).map(&:chr).join # => "foobar"
有没有更好(更简洁)的方法? unpack
会有所帮助吗?
Is there a better (more concise) way? Could unpack
be helpful somehow?
推荐答案
You can use Array#pack
:
["666f6f626172"].pack('H*')
#=> "foobar"
H
是十六进制字符串的指令(高半字节在前).
H
is the directive for a hex string (high nibble first).
这篇关于将十六进制ASCII码的字符串转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文