Python String to hex

1.7k Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

Try specifying that the int is in base 16:

>>> int("0x3f", 16)
63

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 the 0x prefix is present.

>>> import ast
>>> #hexadecimal
>>> ast.literal_eval("0x3f")
63
>>> #binary
>>> ast.literal_eval("0b01010")
10
>>> #octal
>>> ast.literal_eval("0712")
458
>>> #decimal
>>> ast.literal_eval("42")
42
0
On

int takes an optional second argument, which is the numerical base to use for conversion. The default is 10 (decimal conversion) but you can change it to 16 (for hex) or 0 (for automatic conversion based on prefix):

>>> int('0b1010', 0)
10
>>> int('0x3f', 0)
63
>>> int('0o777', 0)
511
>>> int('1234', 0)
1234