Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to convert bytes to integer arrays efficiently?

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)
like image 679
xiaodai Avatar asked May 10 '26 10:05

xiaodai


1 Answers

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

like image 149
xiaodai Avatar answered May 11 '26 23:05

xiaodai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!