4

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 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This answer could be improved by using the with statement (so that the file always gets closed, the code becomes more idiomatic/readable/shorter) and print as a function - as it stands, your program contains a syntax error on current Python versions.
Thank you for the suggestion. It still does the same thing. instead of 4, i tried 148 and the file read (hex view) : c2 94 00
0

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

np.uint16(Current-Start)

Try this:

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

2 Comments

I think that struct.pack('H', np_uint16_instance) is the same as np_uint16_instance.tostring()
This will write a string to the file which is not what I'm looking for. I have update the question, sorry if it wasn't clear before.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.