将十六进制字符串添加到二进制文件的内容中
Prepend hex string to the content of binary file
我有这两个代表十六进制数的数组,我想以二进制格式写入文件。
我像这样转换为十六进制字符串:
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
写入文件,然后将 hex_string1
添加到文件中(偏移量为“0”)。
我正在这样做,但输出不正确。
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
"output.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
我有这两个代表十六进制数的数组,我想以二进制格式写入文件。
我像这样转换为十六进制字符串:
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
写入文件,然后将 hex_string1
添加到文件中(偏移量为“0”)。
我正在这样做,但输出不正确。
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
"output.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