Typing or accessing a char array for an integer array in Python

I have a char array in Python that is being read from a file, for example.

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

how do I convert / typecast / to access this array of integers like

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

similar to how you can access an array of bytes as integers in C / C ++, that is, enter cast unsigned char * in unsigned long *.

+3
source share
2 answers

Something like this is possible:

>>> 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 is a more elegant solution using struct?

+1
source

Not sure if this is the most efficient way, but it looks pretty 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']
0
source

All Articles