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!
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.
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