[英]Python: How to convert bytes to integer arrays efficiently?
I have read a binary file from disk.我已经从磁盘读取了一个二进制文件。 Which produces a bytes variable eg
这会产生一个字节变量,例如
arr = open(file, "rb").read()
Now arr
is structured such that each 4-byte form a 32bit integer (little endian).现在
arr
的结构使得每个 4 字节形成一个 32 位 integer(小端序)。 I see there is function int.from_bytes
to convert bytes to int but it is too slow.我看到有 function
int.from_bytes
将字节转换为 int 但它太慢了。
Is there a function to convert bytes to an integer array?是否有 function 将字节转换为 integer 数组? Numpy solutions welcome.
欢迎 Numpy 解决方案。
In contrast, this seems easy to do in R and Julia eg相比之下,这在 R 和 Julia 中似乎很容易做到,例如
In R在 R
readBin(arr, what="integer", n=length(arr)/4)
In Julia在 Julia
reinterpret(Int32, arr)
Based on @Tim Peter's answer it is根据@Tim Peter 的回答,它是
b = array.array("i")
b.frombytes(arr)
Now b
is an array of int.现在
b
是一个 int 数组。
See documentation here https://docs.python.org/3/library/array.html#module-array请参阅此处的文档https://docs.python.org/3/library/array.html#module-array
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.