我有这两个代表十六进制数字的数组,我想以二进制格式写入文件。
我像这样转换为十六进制字符串:
a=["A2","48","04","03","EE","72","B4","6B"]
b=["1A","28","18","06","07","00","11","86","05","01","01","01","A0"]
hex_string1 = a.map{|b| b.to_i(16)}.pack("C*")
hex_string2 = b.map{|b| b.to_i(16)}.pack("C*")
现在我想先将hex_string2
写入文件,然后在文件前面加上(偏移量为"0")hex_string1
。
我正在像这样进行,但输出不正确。
File.binwrite("outfile.bin",hex_string2)
File.binwrite("outfile.bin",hex_string1,0)
当前输出为:
A2 48 04 03 EE 72 B4 6B 05 01 01 01 A0
"输出.bin"中的正确内容如下所示:
A2 48 04 03 EE 72 B4 6B 1A 28 18 06 07 00 11 86 05 01 01 01 A0
如何做到这一点?
你应该写第二个字符串,偏移量是第一个字符串的大小:
File.binwrite("outfile.bin",hex_string2,hex_string1.size)
File.binwrite("outfile.bin",hex_string1,0)
在这种情况下,你会得到你想要的:
A2 48 04 03 EE 72 B4 6B 1A 28 18 06 07 00 11 86 05 01 01 01 A0