[[string]]。pack('H *')是什么意思? [英] What does ["string"].pack('H*') mean?
本文介绍了[[string]]。pack('H *')是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要将一些Ruby代码翻译成JavaScript,并且遇到以下函数:
def sha1_hex(h)
Digest :: SHA1.hexdigest([h] .pack('H *'))
end
在这种情况下, [h] .pack('H *')
意味着什么?它如何转换为JavaScript?解析方案
它将字符串解释为十六进制数字,每个字节两个字符,并将其转换为字符串与相应的ASCII码字符:
[464F4F]。pack('H *')#=> ; FOO,0x46代表'F',0x4F代码为'O'
相反的转换,使用 unpack
:
'FOO'.unpack 'H *')#=> [464f4f]
非ASCII-8BIT编码有点困难:
á.encoding#=> #<编码:UTF-8是氢。
á.unpack('H *')#=> [c3a1]
['c3a1']。pack('H *')#=> \xC3\xA1
['c3a1']。pack('H *')。encoding#=> #<编码:ASCII-8BIT>
['c3a1']。pack('H *')。force_encoding('UTF-8')#=> á
I need to translate some Ruby code to JavaScript and came across the following function:
def sha1_hex(h)
Digest::SHA1.hexdigest([h].pack('H*'))
end
What exactly does [h].pack('H*')
mean in this context? How would it translate to JavaScript?
解决方案
It interprets the string as hex numbers, two characters per byte, and converts it to a string with the characters with the corresponding ASCII code:
["464F4F"].pack('H*') # => "FOO", 0x46 is the code for 'F', 0x4F the code for 'O'
For the opposite conversion, use unpack
:
'FOO'.unpack('H*') # => ["464f4f"]
It is a little bit more difficult for non-ASCII-8BIT encodings:
"á".encoding # => #<Encoding:UTF-8>
"á".unpack('H*') # => ["c3a1"]
['c3a1'].pack('H*') # => "\xC3\xA1"
['c3a1'].pack('H*').encoding # => #<Encoding:ASCII-8BIT>
['c3a1'].pack('H*').force_encoding('UTF-8') # => "á"
这篇关于[[string]]。pack('H *')是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文