Reputation: 23
I need to export a Int converted string into binary data, so i can use it in a micro-controller.
Here is part of the code:
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
I need to export my "string_hex" into a binary file, not a text.
PS I'm developing in Windows 7.
Upvotes: 2
Views: 89
Reputation: 521
I'm not completely sure if this is what you are looking for, but I believe that you want to do something like the following:
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
The array method pack('L*')
will convert each (4 byte) integers in the string_hex
array into a single string that represents the integers in binary format.
In case you need 8 byte integers you can use pack('Q*')
. Check this link for other available formats.
Here is an example of using 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]
Upvotes: 1