在Ruby中将基数为2的数字字符串数组写入二进制文件 [英] Write array of radix-2 numeric strings to binary file in Ruby

查看:253
本文介绍了在Ruby中将基数为2的数字字符串数组写入二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ruby中编写了一个简单的霍夫曼编码。作为输出,我有一个数组,例如:

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", "110", "000", "10", "011"]

我需要在文件中写入,然后读取文件。我尝试了几种方法:

I need to write, and then read, it to and from a file. I tried several methods:

IO.binwrite("out.cake", array)

我得到一个简单的文本文件,而不是二进制文件。

I get a simple text file and not binary.

或者:

File.open("out.cake", 'wb' ) do |output|
  array.each do | byte |
       output.print byte.chr
  end
end

其中看起来它有效,但后来我无法将其读入数组。

Which looks like it works, but then I can't read it into array.

我应该使用哪种编码?

推荐答案

我认为你可以使用 Array#pack String#unpack 如下代码:

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"

我不知道您阅读结果的首选格式,我知道上述方法效率低下。但无论如何,你可以从 unpack 的结果顺序取0或1来遍历你的霍夫曼树。

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.

这篇关于在Ruby中将基数为2的数字字符串数组写入二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆