简体   繁体   English

Python:将int写入二进制文件

[英]Python: Writing int to a binary file

I have a program which calculates the offset(difference) and then stores them in an 16 bit unsigned int using numPy and I want to store this int into a binary file as it is in binary form. 我有一个计算偏移量(差异)的程序,然后使用numPy将它们存储在16位无符号整数中,我想将这个int存储到二进制文件中,因为它是二进制形式。 ie if the value of offset is 05, I want the file to show "01010000 00000000", but not as a string. 即如果offset的值是05,我希望文件显示“01010000 00000000”,但不是字符串。 The code I have written is: 我写的代码是:

target = open(file_cp, 'wb')
target.write('Entries')
target.write('\n')
Start = f.tell()
while(!EOF):
    f.read(lines)
    Current = f.tell()
    offset = np.uint16(Current-Start)
    target.write(offset)

there is some processing after f.read(lines) but thats sort of the idea. 在f.read(行)之后有一些处理,但那就是这个想法。 The code works fine as long as the offset is less than 127. As soon as the offset goes above 127, a 0xC2 appears in the file along with the binary data. 只要偏移小于127,代码就可以正常工作。一旦偏移超过127,文件中就会出现0xC2和二进制数据。

data in the file appears as follows (hex view, little indian): 00 00 05 00 0e 00 17 00 20 00 3c 00 4e 00 7b 00 c2 8d 00 c2 92 00 c2 9f 00 文件中的数据如下所示(十六进制视图,小印度):00 00 05 00 0e 00 17 00 20 00 3c 00 4e 00 7b 00 c2 8d 00 c2 92 00 c2 9f 00

Could someone suggest a solution to the problem? 有人可以建议解决问题吗?

Try this. 试试这个。

import numpy as np
a=int(4)
binwrite=open('testint.in','wb')
np.array([a]).tofile(binwrite)
binwrite.close()

b=np.fromfile('testint.in',dtype=np.int16)
print b[0], type(b[0])

output: 4 type 'numpy.int16' 输出:4类型'numpy.int16'

I Hope this is wha you are looking for. 我希望这是你要找的。 Works for n>127 But read and writes numpy arrays... binwrite=open('testint.in','ab') will let you append more ints to the file. 适用于n> 127但读取和写入numpy数组... binwrite = open('testint.in','ab')将允许您向文件追加更多的内容。

You should use the built-in struct module. 您应该使用内置的struct模块。 Instead of this: 而不是这个:

np.uint16(Current-Start)

Try this: 尝试这个:

struct.pack('H', Current-Start)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM