Python program to convert hex string to decimal
Last Updated : 10 Jan, 2025
Improve
Converting a hexadecimal string to a decimal number is a common task in programming, especially when working with binary data or low-level computations. Hexadecimal values offer a concise way to represent large numbers.
Using the int()
Function
Using the int() function is the most common and straightforward method.
hex_s = "1A3F"
integer_value = int(hex_s, 16)
print(f"{integer_value}")
Output
6719
Explanation
int(hex_s, 16)
converts the hexadecimal string"1A3F"
to its integer value, interpreting it as base 16.- The
print()
statement uses an f-string to display the result dynamically asUsing
int()
: {integer_value}
.
Using ast.literal_eval
from ast
Module
This method can evaluate the hex string when prefixed with 0x
.
import ast
hex_s = "1A3F"
# Prefix the hex string with '0x' to make it evaluable
integer_value = ast.literal_eval(f"0x{hex_s}")
print(f"{integer_value}")
Output
6719
Explaination
ast.literal_eval(f"0x{hex_s}")
safely evaluates the prefixed string"0x1A3F"
as a hexadecimal number and converts it to an integer.print()
statement dynamically displays the result asUsing ast.literal_eval(): {integer_value}
.
Using struct.unpack
For fixed-width hexadecimal strings, we can convert them using struct.unpack
.
import struct
hex_string = "1A3F"
# Convert hex string to bytes and unpack
integer_value = struct.unpack(">H", bytes.fromhex(hex_string))[0]
print(f"{integer_value}")
Output
6719
Explanation
struct.unpack(">H", bytes.fromhex(hex_string))[0]
converts the hexadecimal string"1A3F"
into bytes usingbytes.fromhex()
and unpacks it as a big-endian 2-byte unsigned integer.- The
print()
statement uses an f-string to display the converted integer asUsing struct.unpack(): {integer_value}
.
Using base64.b16decode
Decode the hex string to bytes, then convert it to an integer.
import base64
hex_string = "1A3F"
# Decode using base64.b16decode
decoded_bytes = base64.b16decode(hex_string)
integer_value = int.from_bytes(decoded_bytes, byteorder="big")
print(f"{integer_value}")
Output
6719
Explanation
base64.b16decode(
hex_string)
decodes the hexadecimal string"1A3F"
into bytes.int.from_bytes(decoded_bytes, byteorder="big")
converts the bytes to an integer, displayed withprint()
.