2016-04-04 10 views
2

Int変換文字列をバイナリデータにエクスポートする必要があるので、マイクロコントローラで使用できます。ここでruby​​ 2.2.4(Windows)でデータをシリアライズしてエクスポートする方法は?

は、コードの一部です:

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」をエクスポートする必要があります。私は、Windows 7で

答えて

1

を開発してい

PSこれはあなたが探しているものであれば、私は完全にわからないんだけど、私はあなたが以下のような何かをしたいと考えてい:

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] 
+0

はどうもありがとう...問題は解決します!それはまさに私が探していたものでした。 –

関連する問題