user974168
user974168

Reputation: 237

converting python list of integers to a hex number

I have library function which reads from hardware and returns

value = readregister(registerindex,numbytes)

where value is a python list.

If numbytes is 2, then the complete returned number will be returned in

value[0],value[1]

For example it returns

    [128,2]

which in hex is

   [0x80,0x2]

How do I convert this list value of 2 elements to a hex python number ? So if combine them I should get 0x280 ie 640

Upvotes: 0

Views: 11808

Answers (2)

Dunes
Dunes

Reputation: 40683

There is no need to convert to an intermediate hex representation. You can just left shift the bits to create the number you want.

def get_number(values):
    total = 0
    for val in reversed(values):
        total = (total << 8) + val
    return total 

Upvotes: 2

Avinash Garg
Avinash Garg

Reputation: 1402

try this:

list=[128,2]
>>> b=[]
>>> for item in list:
...     b.append(hex(item))
... 
>>> b
>>>[0x80,0x2]

Upvotes: 0

Related Questions