Appending hex values to a list/converting string lists to hex

Viewed 323

I have a dataframe where each row is a CAN message which has to be in hex. But when I put the rows into a list, individual values are stored as strings. For example:

['0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x1']

Is there a way to have [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1] instead?

1 Answers

Easy enough! Use the base parameter on the int function to convert from hex string to integer, and you can use hex to go back from integer to hex string.

# Convert hex string to int
str_vals = ['0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x0', '0x1']
int_vals = [int(val, 16) for val in str_vals]
# Convert int to hex string
int_vals = [0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1]
str_vals = [hex(val) for val in int_vals]
Related