Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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!

share|improve this question

3 Answers 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'
share|improve this answer
1  
What if some elements of A are < 0x10? –  John La Rooy 8 mins ago

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
share|improve this answer
A = [0xaa, 0xbb, 0xcc]
d = reduce(lambda x, y: x*256 + y, A)
print hex(d)
share|improve this answer
    
I suggest you to use x << y.bit_length() instead of x*256 to make your code more flexible –  Alik 16 mins ago
2  
@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. –  dlask 13 mins ago
1  
Oh, I didn't think about the question this way. I think OP should clarify what he wants to do. –  Alik 10 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.