简体   繁体   中英

How to convert python list of interger to list of hex, getting List error “struct.error: required argument is not an integer”

I have a list that is the a=[0,1] and I want to change with a=[0x00,0x001] type. How can I do this? I tried this way

print (struct.pack('>h',a))

But I cannot change to hex

Using hex directly should work:

>>> a = [0,1]
>>> a = [hex(i) for i in a]
>>> a
['0x0', '0x1']

Using hex(...) will only give you the least amount of leading 0:

print( [hex(i) for i in [0,1]])  #  ['0x1', '0x2']

You can format(...) the string as hex and zfill() the needed amount of zeros and prepending '0x' to it yourself:

data = [0,1]

as_hex = [ "0x" + format(e,"x").zfill(2) for e in data]

print(as_hex)

Output:

['0x00', '0x01']

As you fail to describe what your wanted outcome is, I can only guess:

  1. Do you want to pack some numbers to a string?

    Then it doesn't matter which format you use, both should work as soon as you use the correct format string:

     a = [1, 2] b = [0x01, 0x02] struct.pack(">hh", *a) # > '\\x00\\x01\\x00\\x02' struct.pack(">hh", *b) # > '\\x00\\x01\\x00\\x02' 

    This is because a and b are equal: it doesn't matter if you write 1 and 2 or if you prefer 0x01 resp. 0x02 . Be aware that the displayed strings are just representations of strings containing special characters with the values 0, 1 and 2, respectively.

  2. Do you want to output your numbers in a hexadecimal representation?

    In this case, see the other answers.

Below is the another way of converting you list of integer to list of hex

a = [0,1]
b = map(hex, a) 
# or 
b = map(lambda x:hex(x), a)
# output
print b
['0x1', '0x2']

Below is the another way of converting a list of integer to list of hex using a map function:

a=[0,1]
print(map(hex,a))
# Output
# ['0x0', '0x1']

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