Python: Convert array into integer

1.8k views Asked by At

I was wondering if there is a way in Python to convert an array or a list into one single number:

A=[0xaa,0xbb,0xcc]

d=0xaabbcc

Thanks for your help!

3

There are 3 answers

3
dlask On
A = [0xaa, 0xbb, 0xcc]
d = reduce(lambda x, y: x*256 + y, A)
print hex(d)
1
TigerhawkT3 On

Use hex(), map(), and join().

>>> '0x' + ''.join(map(hex, A)).replace('0x', '')
'0xaabbcc'

Or with lambda:

>>> '0x' + ''.join(map(lambda x: hex(x)[2:], A))
'0xaabbcc'

Thanks to @John La Rooy for pointing out that this fails with 1-digit numbers. The following modification of the lambda version is better:

>>> B = [0x1, 0x4, 0x3]
>>> '0x' + ''.join(map(lambda x: hex(x)[2:].rjust(2, '0'), B))
'0x010403'

But at that point it's better to use John's answer.

0
John La Rooy On

For Python3+, int has a method for this

>>> A=[0xaa, 0xbb, 0xcc]
>>> hex(int.from_bytes(A, byteorder="big"))
'0xaabbcc'

>>> 0xaabbcc == int.from_bytes(A, byteorder="big")
True

For Python2, it's probably best to write a small function

>>> A = [0xaa, 0xbb, 0xcc]
>>> 
>>> def to_hex(arr):
...     res = 0
...     for i in arr:
...         res <<= 8
...         res += i
...     return res
... 
>>> 0xaabbcc == to_hex(A)
True