I have a string that can be a hex number prefixed with "0x" or a decimal number without a special prefix except for possibly a minus sign. "0x123" is in base 16 and "-298" is in base 10.
How do I convert this to an int or long in Python?
I don't want to use eval() since it's unsafe and overkill.
To convert a hexadecimal string to an integer, pass the string as a first argument into Python's built-in int() function. Use base=16 as a second argument of the int() function to specify that the given string is a hex number.
Python module provides an int() function which can be used to convert a hex value into decimal format. It accepts 2 arguments, i.e., hex equivalent and base, i.e. (16). int() function is used to convert the specified hexadecimal number prefixed with 0x to an integer of base 10.
Parse int to string in Python We can use the inbuilt str() function to parse Python int to String to convert an integer to String. Parsing is the same as converting in programming.
In base 16 (also called "hexadecimal" or "hex" for short) you start at 0 then count up 0123456789ABCDEF (16 digits in total). The int function accepts any number from 2 and 36 as the base, it just extends the alphabet: base 36 is 0123456789ABCEDFGHIJKLMNOPQRSTUVWXYZ .
int("0x123", 0)
(why doesn't int("0x123")
do that?)
Base 16 to 10 (return an integer):
>>> int('0x123', 16) 291
Base 10 to 16 (return a string):
>>> hex(291) '0x123'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With