3

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 Answers 3

5

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
Sign up to request clarification or add additional context in comments.

Comments

3

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.

1 Comment

What if some elements of A are < 0x10?
2
A = [0xaa, 0xbb, 0xcc]
d = reduce(lambda x, y: x*256 + y, A)
print hex(d)

3 Comments

I suggest you to use x << y.bit_length() instead of x*256 to make your code more flexible
@Alik You are right, but only if the original question wants to deal with bits instead of bytes. Please note that for a = 1 the a.bit_length() gives 1.
Oh, I didn't think about the question this way. I think OP should clarify what he wants to do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.