Ruby's pack and unpack explained

后端 未结 4 551
长发绾君心
长发绾君心 2021-02-08 04:40

Even after reading the standard documentation, I still can\'t understand how Ruby\'s Array#pack and String#unpack exactly work. Here is the example that\'s causing me the most t

4条回答
  •  死守一世寂寞
    2021-02-08 05:03

    I expected both these operations to return the same output: "abc".

    The easiest way to understand why your approach didn't work, is to simply start with what you are expecting:

    "abc".unpack("H*")
    # => ["616263"]
    
    ["616263"].pack("H*")
    # => "abc"
    

    So, it seems that Ruby expects your hex bytes in one long string instead of separate elements of an array. So the simplest answer to your original question would be this:

    chars = ["61", "62", "63"]
    [chars.join].pack("H*")
    # => "abc"
    

    This approach also seems to perform comparably well for large input:

    require 'benchmark'
    
    chars = ["61", "62", "63"] * 100000
    
    Benchmark.bmbm do |bm|
      bm.report("join pack") do [chars.join].pack("H*") end
      bm.report("big pack") do chars.pack("H2" * chars.size) end
      bm.report("map pack") do chars.map{ |s| [s].pack("H2") }.join end
    end
    
    #                 user     system      total        real
    # join pack   0.030000   0.000000   0.030000 (  0.025558)
    # big pack    0.030000   0.000000   0.030000 (  0.027773)
    # map pack    0.230000   0.010000   0.240000 (  0.241117)
    

提交回复
热议问题