3

I have read a binary file from disk. Which produces a bytes variable e.g.

arr = open(file, "rb").read()

Now arr is structured such that each 4-byte form a 32bit integer (little endian). I see there is function int.from_bytes to convert bytes to int but it is too slow.

Is there a function to convert bytes to an integer array? Numpy solutions welcome.

In contrast, this seems easy to do in R and Julia e.g.

In R

readBin(arr, what="integer", n=length(arr)/4)

In Julia

reinterpret(Int32, arr)
1
  • 1
    See Python array module. Format code for 4-byte signed ints is 'l'. The .frombytes() method for what you asked, or the .fromfile() method to construct directly by a reading from an open binary-mode file. Commented Apr 26, 2020 at 4:06

1 Answer 1

1

Based on @Tim Peter's answer it is

b = array.array("i")
b.frombytes(arr)

Now b is an array of int.

See documentation here https://docs.python.org/3/library/array.html#module-array

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

Comments

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.