Python: Writing int to a binary file

2019-06-26 02:22发布

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. i.e. if the value of offset is 05, I want the file to show "01010000 00000000", but not as a string. 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. 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.

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

Could someone suggest a solution to the problem?

2条回答
啃猪蹄的小仙女
2楼-- · 2019-06-26 02:56

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'

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.

查看更多
We Are One
3楼-- · 2019-06-26 02:57

You should use the built-in struct module. Instead of this:

np.uint16(Current-Start)

Try this:

struct.pack('H', Current-Start)
查看更多
登录 后发表回答