Search code examples
python-3.xhexuint32-t

In python: unable to convert variable with uint32_t, uint8_t, int16_t value to hexadecimal


I have a .ini file with values as below

[Value1]
data_type = uint16_t
value = 0x0001U


[Value2]
data_type = uint32_t
value = 0x00000002UL

[Value4]
data_type = uint8_t
value = 5U

I am unable to convert these values to hexadecimal as below Comment: I am easily able to read .ini file using configparser. Let assume i have value as string in variable var and I want to convert that string variable to hex form

print (hex(var)) #this should print the  hexadecimal value 

Solution

  • This doesn't work:

    var = '0x00000002UL'
    hex(var)
    

    Because hex() is meant to convert in the opposite direction. Instead, try this:

    var = '0x00000002UL'
    int(var[:-2], 16)
    

    Note you need to skip the UL on the end because that's not Python syntax.