在Python 2.7中将bytearray解释为long数组


Python 3中,可以通过memoryview.cast()将底层内存解释为字节数组或整数或长整数:

[] b=bytearray(2*8)
[] b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')
[] m=memoryview(b).cast('L') #reinterpret as an array of unsigned longs
[] m[1]=2**64-1
[] b
bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff')

可以看出,我们可以在memoryview m的帮助下访问bytearray b,好像它是无符号long数组(在我的机器上长8字节).

但是,在Python 2.7中,memoryview lacks的方法是强制转换的.

因此我的问题是:是否有可能在Python 2.7中将bytearray重新解释为long数组?

在不复制/分配更多内存的情况下执行此操作非常重要.

通过我的机器上的T [i]读取长值所需的时间(Python 3.4):

python list:                40ns  (fastest but needs 24 bytes per element)
python array:              120ns  (has to create python int-object)
memoryview of bytearray    120ns  (the same as array.array)
Jean-François's solution: 6630ns  (ca. 50 times slower)
Ross's solution:           120ns

最佳答案 您可以使用ctypes及其
from_buffer方法创建一个与stringarray对象共享其内存的无符号long的ctypes数组.

例如:

import ctypes

ba = bytearray(b'\x00' * 16)
a = (ctypes.c_ulong * (len(ba) / 8)).from_buffer(ba)
a[1] = -1
print repr(ba)
点赞