简体   繁体   English

在Python中类型化或访问char数组到整数数组

[英]Typecasting or accessing char array to integer array in Python

I have a char array in Python, which is read from a file eg 我在Python中有一个char数组,它从文件中读取,例如

char_array = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]

how do i convert/typecast/access this to an array of integers like 我如何转换/类型转换/访问这个整数数组

int_array[0] = 0x03020100
int_array[1] = 0x07060504
int_array[2] = 0x0b0a0908
int_array[3] = 0x0f0e0d0c

similar to how one would access an array of bytes as integers in C/C++ ie type cast an unsigned char * to an unsigned long *. 类似于如何在C / C ++中以整数形式访问字节数组,即将unsigned char *类型转换为unsigned long *。

something like this maybe: 这样的事情可能是:

>>> def toInt(arr, idx):
...     res = 0
...     for i in xrange(4):
...       res |= (arr[idx*4 + i] << 8*i)
...     return res
... 

>>> '%08x' % toInt(char_array, 0)
'03020100'

>>> '%08x' % toInt(char_array, 1)
'07060504'

maybe there's a more elegant solution using struct ? 也许使用struct更优雅的解决方案?

Not sure if it's the most efficient way, but looks quite elegant: 不确定它是否是最有效的方式,但看起来非常优雅:

from itertools import izip_longest
from struct import pack_into, unpack_from

def convert(bytes):
    it = iter(bytes)
    arr = bytearray(4)
    buf = buffer(arr)
    # a grouping trick (see itertools examples)
    for group in izip_longest(*[it]*4, fillvalue=0):
        # pack 4 bytes, then unpack high-endian
        pack_into('bbbb', arr, 0, *group)            
        intval, = unpack_from('<i', buf)
        yield hex(intval)


char_array = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f]

print list(convert(char_array))
# ['0x3020100', '0x7060504', '0xb0a0908', '0xf0e0d0c']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM