Write array of radix-2 numeric strings to binary file in Ruby

前端 未结 2 1360
Happy的楠姐
Happy的楠姐 2021-01-01 15:10

I\'ve written a simple Huffman encoding in Ruby. As output I\'ve got an array, for example:

[\"010\", \"1111\", \"10\", \"10\", \"110\", \"1110\", \"001\", \         


        
2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 16:06

    I think you can just use Array#pack and String#unpack like the following code:

    # Writing
    a = ["010", "1111", "10", "10", "110", "1110", "001", "110", "000", "10", "011"]
    File.open("out.cake", 'wb' ) do |output|
      output.write [a.join].pack("B*")
    end
    
    # Reading
    s = File.binread("out.cake")
    bits = s.unpack("B*")[0] # "01011111010110111000111000010011"
    

    I don't know your preferred format for the result of reading and I know the above method is inefficient. But anyway you can take "0" or "1" sequentially from the result of unpack to traverse your Huffman tree.

提交回复
热议问题