Explain Codes LogoExplain Codes Logo

Convert hex string to integer in Python

python
functions
error-handling
validation
Alex KataevbyAlex Kataev·Aug 24, 2024
TLDR

Convert a hexadecimal string to an integer in Python fast just like ripping off a band-aid, using int() with base 16:

integer_value = int("1a", 16) print(integer_value) # 26

This returns the integer 26 from hex string "1a".

Detailed breakdown

Let's understand this with some practical examples and clear out the mystery behind these conversions, like a Sherlock Holmes of hexadecimal:

  • Hex without prefix: If a hex string does not include the "0x" prefix, just wake up the int() function with a base of 16:
integer_no_prefix = int("deadbeef", 16) print(integer_no_prefix) # Prints: Some morbidly large integer
  • With prefix: On the contrary, if your hex string includes the "0x" prefix, Python, like an attentive butler, does the job without any hints:
integer_prefix = int("0xdeadbeef") print(integer_prefix) # Prints: Same enormous integer

Error handling mechanism

Nobody's perfect, not even strings. They might throw exceptions during hex conversion. For that, shield the code with a try-except block to catch those naughty strings:

hex_string = "not_a_hex" try: value_bad_string = int(hex_string, 16) except ValueError: print("Oops! It seems not all strings can be hex strings!")

Brewing a perfect converter

We aim for perfection! Let's debate over all possibilities and edge cases like politically aware programmers. Empty strings, strings with extraterrestrial characters, or even negative hex values, our function has got it covered:

def convert_hex_to_int(hex_string): """Converts hex string to integer, even if it has a bad mood (negative)!""" if hex_string.startswith('-'): mood = -1 hex_string = hex_string[1:] else: mood = 1 return mood * int(hex_string, 16) ### Highlighting key points Python is smart enough to **deduce the base** when the `0x` or `0X` prefix is present: ```python print('Guess the base:', int('0x10')) # Python guesses base 16 = 16

However, the int() function needs more caffeine (or base 16) when the prefix is asleep:

print('Specify the base:', int('10', 16)) # Base 16 = 16

The art of validation

To avoid runtime errors, preach the habit of validation before conversion. Here's how:

import re def validate_hex(hex_string): """Checks if a hex string is as honest as Abe Lincoln.""" match = re.fullmatch('-?0x[0-9a-fA-F]+$', hex_string) or re.fullmatch('-?[0-9a-fA-F]+$', hex_string) return bool(match) hex_string = "0x1A" if validate_hex(hex_string): value_valid_string= int(hex_string, 16) print('It is valid! Value:', value_valid_string) else: print("Sorry! That hex string failed the test.")