[英]Write binary file in Ruby
Is there a simple way to write binary data into binary file like we used to do in C/C++? 是否有一种简单的方法将二进制数据写入二进制文件,就像我们在C / C ++中所做的那样? For example, how can I create a 4-byte file with serialized 4-byte integer value without using fancy math?
例如,如何在不使用花哨数学的情况下创建具有序列化4字节整数值的4字节文件?
You can use Array#pack and String#unpack to convert to and from binary representations. 您可以使用Array#pack和String#unpack来转换为二进制表示形式。 Combine them with IO#write and IO#read , and away you go.
将它们与IO#write和IO #read结合起来,然后就可以了。
I recently had a similar problem for work. 我最近有一个类似的工作问题。 I used the BinData gem and it worked a treat.
我使用了BinData宝石,它起了作用。 You just do something like:
你只需做一些事情:
File.open('test.bin', 'wb') {|file| BinData::Int32be.new(12345).write(file) }
and you don't need to remember any Array#pack
codes. 而且您不需要记住任何
Array#pack
代码。
There are Marshal.dump
and Marshal.load
methods you can use. 您可以使用
Marshal.dump
和Marshal.load
方法。
Here's a link: http://en.wikipedia.org/wiki/Serialization#Ruby . 这是一个链接: http : //en.wikipedia.org/wiki/Serialization#Ruby 。
And another that saves the data to a file: http://rubylearning.com/satishtalim/object_serialization.html . 另一个将数据保存到文件: http : //rubylearning.com/satishtalim/object_serialization.html 。
In my humble oppinion, ruby wasn't made for such tasks. 在我的拙见中,红宝石不是为了这样的任务而做的。 If you have to write to binary files a lot, it would be easiest to write some c functions for that and call them from ruby, which is quite easy using swig.
如果你必须经常写二进制文件,最简单的方法是为它编写一些c函数并从ruby中调用它们,这很容易使用swig。 I'm doing the same thing at the moment to write a raid simulator.
我正在做同样的事情来写一个raid模拟器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.