Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
911 views
in Technique[技术] by (71.8m points)

ruby - What does ["string"].pack('H*') mean?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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*')                         # => "xC3xA1"
['c3a1'].pack('H*').encoding                # => #<Encoding:ASCII-8BIT>
['c3a1'].pack('H*').force_encoding('UTF-8') # => "á"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...