In Python, you can convert a hexadecimal string to an integer using the built-in int()
function. This function takes two arguments: the string to be converted and the base of the number in the string.
To convert a hexadecimal string to an integer, you need to specify the base as 16. You can do this by passing 16 as the second argument to the int()
function. Here’s an example:
hex_string = "ffff"
integer = int(hex_string, 16)
print(integer) # Output: 65535
If your hexadecimal string starts with the 0x
prefix, you can still convert it to an integer by specifying the base as 16. However, if you pass 0 as the base, Python will automatically detect the base from the prefix.
hex_string_with_prefix = "0xffff"
integer_with_prefix = int(hex_string_with_prefix, 16)
print(integer_with_prefix) # Output: 65535
# Alternatively, you can use base 0 to let Python infer the base
integer_inferred_base = int(hex_string_with_prefix, 0)
print(integer_inferred_base) # Output: 65535
Note that if your hexadecimal string does not start with the 0x
prefix and you try to convert it with base 0, Python will raise a ValueError
.
hex_string_without_prefix = "ffff"
try:
integer_without_prefix = int(hex_string_without_prefix, 0)
except ValueError as e:
print(e) # Output: invalid literal for int() with base 0: 'ffff'
It’s worth noting that if you’re typing a hexadecimal number directly into your Python code or an interpreter, you don’t need to use the int()
function. Python will automatically convert it to an integer.
hex_literal = 0xffff
print(hex_literal) # Output: 65535
However, this only works if the hexadecimal number starts with the 0x
prefix. Without the prefix, Python will treat it as a variable name and raise a NameError
.
try:
hex_variable = ffff
except NameError as e:
print(e) # Output: name 'ffff' is not defined
In summary, to convert a hexadecimal string to an integer in Python, you can use the int()
function with base 16. If your string starts with the 0x
prefix, you can also use base 0 to let Python infer the base.