Which means ["string"]. Pack ('H *')?

I need to translate Ruby code into JavaScript and stumbled upon 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 to translate this into JavaScript?

+7
ruby hex digest
source share
1 answer

It interprets the string as hexadecimal numbers, two characters per byte, and converts it into a string with 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"] 

This is a bit more complicated for encodings without ASCII-8BIT:

 "รก".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') # => "รก" 
+9
source share

All Articles