Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join list of integers into one integer python

Given a list of hex integers, I want to end up with one hex integer where the integers are treated as most-significant first and least-significant last.

For example, given... [0x1A, 0xF3, 0x74, 0xA3]

...I want to end up with 0x1AF374A3

In another programming language that I'm familiar with this is a fairly simple operation called "join", but apparently "join" means something else in Python.

I know I can iterate through the list multiplying each subsequent element by 2^something and adding them. I also know I can convert the elements to strings, concatenate them and then convert back to integer. But both those approaches seem clunky. Seems like there should be a simpler / more elegant way. Is there?

Thanks in advance for any help!

like image 851
Akash Sharma Avatar asked Aug 24 '18 11:08

Akash Sharma


People also ask

How do you concatenate a list of characters in Python?

You can concatenate a list of strings into a single string with the string method, join() . Call the join() method from 'String to insert' and pass [List of strings] . If you use an empty string '' , [List of strings] is simply concatenated, and if you use a comma , , it makes a comma-delimited string.


1 Answers

I suggest you to switch the values to bytes type in order to concatenate them, them switch back to int type, as follows:

myList = [0x1A, 0xF3, 0x74, 0xA3]
# Conversion to 'bytes'
a = bytes()
for b in myList:
    a += b.to_bytes(1,'big')
# Conversion back to 'int'
a = int.from_bytes(a, 'big')
print(hex(a))  # 0x1af374a3

And you can replace the classic for loop with a generator comprehension passed as parameter to join() method, in order to concatenate the bytes items. It is still readable and a bit shorter, as follows:

myList = [0x1A, 0xF3, 0x74, 0xA3]
a = b''.join(b.to_bytes(1,'big') for b in myList) # Conversion to 'bytes'
a = int.from_bytes(a, 'big')                      # Conversion back to 'int'
print(hex(a))  # 0x1af374a3

Note that if an integer in the input list exceeds 255, then you logically get the error OverflowError: int too big to convert due to b.to_bytes(1,'big'). Of course it can be improved by managing the exception if this case can happen.

I finally may also suggest you the solution using the multiplication by powers of 256, just to show you that it can be achieved in only one-line:

myList = [0x1A, 0xF3, 0x74, 0xA3]
a = sum(nb*(256**i) for i,nb in enumerate(reversed(myList)))
print(hex(a))  # 0x1af374a3
like image 81
Laurent H. Avatar answered Sep 19 '22 13:09

Laurent H.