我有以下python代码,它从二进制文件读取字节字符串,并将其写入另一个二进制文件。
for a in range(nb_acc):
# read buffer value as bytestring of lenght 2 bytes
buffer = lib_decode.f_read_value(fl_bin, 'INT16S')
if a == reqrd_acc_idx:
# print the buffer value as hex to verify the read value
print ''.join( [ "%02X " % ord( x ) for x in buffer ] ).strip()
# write the verified buffer value into another binary file
fl_out.write(buffer)
print()
语句的输出是:
FC DF
但是很奇怪,二进制文件中以十六进制格式获得的write()
语句的输出是:
ef a3 85 e0 b8 bf
write语句的输出与print语句完全不同。在这里,将验证print语句的输出的值和大小(INT16S的大小)正确。而write语句的输出似乎是随机的,并且大小也不正确(6个字节)。仅在某些时候(大多数情况下,其他时间),才可以看到此行为。
有人知道我为什么会得到这种奇怪的随机行为吗?
这应该解决它:
for a in range(nb_acc):
# read buffer value as bytestring of lenght 2 bytes
buffer = lib_decode.f_read_value(fl_bin, 'INT16S')
if a == reqrd_acc_idx:
# print the buffer value as hex to verify the read value
buffer = ''.join( [ "%02X " % ord( x ) for x in buffer ] ).strip()
print(buffer)
# write the verified buffer value into another binary file
fl_out.write(buffer)