So, I've been banging my head against the wall for too long on what seems like it should be an easy data conversion. I am writing in python and passing to another module a hex value that is converted with a wrapper to c type uint_64t. the problem is I am getting this hex value via the python library argparse. When it takes in this value, for example lets use the value 0x3f, it saves it as a string. If I try to cast this as an int it throws the error:
"ValueError: invalid literal for int() with base 10: '0x3f'"
If I create a variable hex = 0x3f however, when I print it out, it gives me the appropriate integer value. (which is great since I'm creating a uint) I am just confused how to make the conversion from string to int if a cast doesn't work. I have seen plenty of examples on turning this string into a hex value by letter (in other words take each individual character of the ascii string '0x3f' and give it a hex value) but I haven't been able to find an example of the situation I am looking for. Apologies if I'm bringing up something that has been answered time and again.
Try specifying that the int is in base 16:
You could also use
ast.literal_eval
, which should be able to read any string that could be used as an integer literal. You don't even have to specify a base for this one, as long as the0x
prefix is present.