简体   繁体   中英

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

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 

try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM