Search code examples
pythonstringnumpybinaryfiles

reading char data from binary file with numpy


I have a binary file with some character data stuck in the middle of a bunch of ints and floats. I am trying to read with numpy. The farthest I have been able to get regarding the character data is:

strbits = np.fromfile(infile,dtype='int8',count=73)

(Yes, it's a 73-character string.)

Three questions: Is my data now stored without corruption or truncation in strbits? And, can I now convert strbits into a readable string? Finally, should I be doing this in some completely different way?

UPDATE: Here's something that works, but I would think there would be a more elegant way.

strarr = np.zeros(73,dtype='c')
for n in range(73):
   strarr[n] = np.fromfile(infile,dtype='c',count=1)[0]

So now I have an array where each element is a single character from the input file.


Solution

  • The way you're doing it is fine. Here's how you can convert it to a string.

    strbits = np.fromfile(infile, dtype=np.int8, count=73)
    a_string = ''.join([chr(item) for item in strbits])