如何在ruby 2.2.4 (Windows)中序列化和导出数据?

How to serialize and export data in ruby 2.2.4 (Windows)?

我需要将 Int 转换后的字符串导出为二进制数据,以便在微控制器中使用它。

部分代码如下:

def save_hex

 text_hex = File.new("hex_#{@file_to_translate}.txt", "a+")

 @text_agreschar.each_with_index do |string_agreschar, index|
  string_hex = ''
  string_agreschar.each do |char_agreschar|
    string_hex << char_agreschar.agres_code.to_i
  end
  text_hex.print(string_hex)
  text_hex.puts('')
 end
end

我需要将我的 "string_hex" 导出到二进制文件,而不是文本文件。

PS 我正在开发 Windows 7.

我不完全确定这是否是您要查找的内容,但我相信您想要执行以下操作:

def save_hex

  text_hex = File.new("hex_#{@file_to_translate}.txt", "a+")

  @text_agreschar.each do |string_agreschar|
    string_hex = [] # create empty array instead of string
    string_agreschar.each do |char_agreschar|
      string_hex << char_agreschar.agres_code.to_i
    end
    text_hex.puts(string_hex.pack('L*')) # convert to "binary" string
  end
end

数组方法 pack('L*') 会将 string_hex 数组中的每个(4 字节)整数转换为表示二进制格式整数的单个字符串。

如果您需要 8 字节整数,您可以使用 pack('Q*')。检查 this link 以了解其他可用格式。

这里是一个使用Array#pack的例子:

i = 1234567

p(i.to_s(16))
#=> "12d687"

p([i].pack('L*'))
#=> "@\xE2\x01\x00"

p([i].pack('L>*')) # force big-endian
#=> "\x00\x12\xD6\x87"

p([i].pack('L>*').unpack('C*')) # reverse the operation to read bytes
#=> [0, 18, 214, 135]