Convert Hexadecimal Numbers to Decimal
How to convert a hex string to decimal in Python, what the conversion keeps and drops, and when to keep the hexadecimal form. Includes PHP notes and worked examples.
Converting hexadecimal to decimal changes how a number is written, not what it is. The hex string 2F and the decimal string 47 name the same integer. The decision is whether the decimal form serves your purpose better than the hex form, and whether your conversion step keeps the details you need: width, sign, byte order and precision. This guide covers the conversion in Python first, then the general algorithm, PHP, and the points where conversions tend to go wrong.
Is converting to decimal the right choice?
Convert to decimal when people or systems need ordinary base-10 numbers: arithmetic, comparisons, reports, form fields, or software that only accepts decimal input. The main benefit is familiarity. Most readers and most tools understand decimal without extra context.
The main tradeoff is lost structure. In hex, each digit maps to exactly four bits, and every pair of digits maps to one byte. That makes hex easy to read for memory addresses, bit masks, colour codes, hashes and protocol dumps. The decimal equivalent of a value like 0xFF00FF00 is 4278255360, which hides the byte pattern. Leading zeros and the intended field width also disappear unless you record them separately.
Keep the hexadecimal form when it is the convention of the destination, such as debugger output, CSS colours, checksums, cryptographic keys and hashes, or anywhere the original string must be reproduced exactly. In those cases, store the hex text and convert to decimal only at the point where a number is needed.
What the conversion actually changes
This is a change of numeral base. Each hex digit carries a value from 0 to 15 (0–9, then A–F or a–f). Each position is worth a power of 16. The output is a new string of decimal digits for the same integer. It is not a character-level edit. Nothing is reversed, mirrored, or restyled, and the result contains only the ASCII characters 0–9, plus a minus sign for negative values.
"Hex string" can mean two different things, and they need different code:
- A single number written in hex, such as "1A3F" or "0x1A3F". Converting it gives one integer (6719).
- A sequence of bytes encoded as hex, such as "48656c6c6f". Decoding it gives bytes (here the ASCII text Hello), or one decimal value per byte (72, 101, 108, 108, 111). It can also be read as one large integer, but only if you know the intended byte order.
Searches for "decode hex to decimal" often mean the second case. Check which one your data is before choosing a function.
Worked examples
These values follow directly from the positional rule (first digit × 16 + second digit):
| Hex | Calculation | Decimal |
| E | 14 | 14 |
| 21 | 2 × 16 + 1 | 33 |
| 27 | 2 × 16 + 7 | 39 |
| 2F | 2 × 16 + 15 | 47 |
| 44 | 4 × 16 + 4 | 68 |
| FF | 15 × 16 + 15 | 255 |
| 1234 | 1 × 4096 + 2 × 256 + 3 × 16 + 4 | 4660 |
Converting a hex string to decimal in Python
The built-in int() function takes a string and a base. With base 16, it returns a Python integer. When you print that integer, or pass it to str(), you get its decimal form.
>>> int("ff", 16)
255
>>> int("0xFF", 16) # the 0x prefix is accepted with base 16
255
>>> int(" 1a3f ", 16) # surrounding whitespace is ignored
6719
>>> int("ff_ff", 16) # single underscores between digits are allowed
65535
>>> int("-2f", 16)
-47
If your input may be written in hex, octal or decimal, pass base 0. Python then reads the base from the prefix (0x, 0o, 0b, or none for decimal). With base 0, a bare "ff" is rejected because it has no 0x prefix.
>>> int("0x2f", 0)
47
>>> int("47", 0)
47
Invalid characters raise ValueError rather than being skipped. Handle that explicitly when the input comes from users or files:
def hex_to_int(text):
try:
return int(text, 16)
except ValueError:
raise ValueError(f"not a hexadecimal number: {text!r}")
Hex-encoded bytes in Python
For byte data, use bytes.fromhex(). It ignores whitespace between byte pairs. To get one decimal value per byte, iterate over the result. To get a single integer, use int.from_bytes() and state the byte order.
>>> data = bytes.fromhex("48 65 6c 6c 6f")
>>> data
b'Hello'
>>> list(data)
[72, 101, 108, 108, 111]
>>> int.from_bytes(bytes.fromhex("1234"), "big")
4660
>>> int.from_bytes(bytes.fromhex("3412"), "little")
4660
Byte order is the one place where reversing is relevant, and it applies to bytes, not characters. A little-endian value stored as "3412" represents 0x1234. Reversing the string character by character would give "2143", which is wrong. Reverse whole byte pairs, or let int.from_bytes() handle it with "little".
Signed values
int("ff", 16) always returns 255. If the hex represents a signed two's-complement field, such as a 16-bit sensor reading, the sign depends on the field width. That width is not in the string itself, so you must supply it:
>>> int.from_bytes(bytes.fromhex("ff"), "big", signed=True)
-1
>>> def to_signed(value, bits):
... return value - (1 << bits) if value >= 1 << (bits - 1) else value
...
>>> to_signed(int("fffe", 16), 16)
-2
The algorithm behind any hex-to-decimal converter
The standard method reads digits from left to right. For each digit, it multiplies the running total by 16 and adds the digit's value. This avoids computing powers of 16 separately, and it is what you would write in a language without a built-in parser:
def hex_to_int_manual(text):
digits = "0123456789abcdef"
text = text.strip().lower()
if text.startswith("0x"):
text = text[2:]
if not text:
raise ValueError("empty input")
total = 0
for ch in text:
value = digits.find(ch)
if value < 0:
raise ValueError(f"invalid hex digit: {ch!r}")
total = total * 16 + value
return total
For "2F", this computes 0 × 16 + 2 = 2, then 2 × 16 + 15 = 47. In Python, prefer int(text, 16) in real code. The manual version is useful for understanding the method or for porting it.
Converting hex to decimal in PHP
PHP's hexdec() takes a hex string and returns its value. Two documented behaviours differ from Python. First, hexdec() ignores characters that are not hex digits instead of rejecting the input; since PHP 7.4, this also emits a deprecation notice. Second, if the value exceeds PHP_INT_MAX, it returns a float, which can lose precision.
<?php
echo hexdec("ff"); // 255
echo hexdec("2f"); // 47
Because of the first behaviour, validate the input before calling hexdec(), for example with ctype_xdigit() after removing any 0x prefix. Otherwise a malformed string may be converted silently into the wrong number. For values larger than the native integer range, use an arbitrary-precision extension such as GMP rather than hexdec().
Will the decimal result stay usable after copying or sharing?
A decimal number is plain ASCII digits, so copy and paste does not change its characters. That is unlike styled Unicode text, which can break in some destinations. The risks are about what the receiving software does with the number, and about information the conversion dropped:
- Leading zeros and width: "00ff" and "ff" both become 255. If you need the original width when converting back, use a fixed-width format such as format(255, "04x"), which gives "00ff", or f"{255:#06x}", which gives "0x00ff".
- Precision in other software: JavaScript numbers represent integers exactly only up to 9007199254740991. Spreadsheet applications commonly keep about 15 significant digits. Large values, such as 64-bit IDs or hashes converted to decimal, can be silently rounded when pasted or parsed there. Keeping such values as text, or as hex, avoids this.
- Spreadsheet functions: Excel's HEX2DEC accepts at most 10 hex characters and treats the top bit of a 10-character input as a sign bit. Longer inputs are out of its range, and a 10-character value starting with 8–F comes back negative.
- Very large integers in Python: since Python 3.10.7 / 3.11, converting an integer with more than 4300 decimal digits to a string raises ValueError by default. Parsing hex is not limited, because base 16 is a power of two, but printing the decimal result is. The limit can be changed with sys.set_int_max_str_digits().
- Search and cross-referencing: if logs, documentation or debuggers show the value in hex, a decimal copy will not match a text search for the hex form. Keep both forms where people need to cross-reference.
Readability: a short decimal value is generally easier for most readers than hex. A long one, such as a converted memory address, is harder to scan than its hex form because it loses the regular digit grouping. For hex address to decimal conversions, keep the hex alongside the decimal value. No testing with specific screen readers or other assistive technology was done for this article, so it makes no claims about how they announce long digit strings.
Online hex to decimal converters
An online hex-dec converter is convenient for one-off values, like checking that E is 14 or 44 is 68. The arithmetic is simple, so the practical differences between tools lie elsewhere. Some accept a 0x prefix and some do not. Some support negative or two's-complement input. Some handle values beyond 64 bits. Some reject invalid characters and others ignore them. No specific converter was tested for this article.
You cannot judge a site's privacy or data retention from its appearance or its claims. If the value is sensitive, such as a key, token, internal address or customer identifier, convert it locally. A one-line Python call does the job without sending the value anywhere.
Summary recommendation
In Python, use int(text, 16) for a single hex number, and bytes.fromhex() with int.from_bytes() for byte data with a known byte order. Decide in advance how you will handle sign, width and invalid input, because the hex string alone does not carry that information. Convert to decimal when the destination expects ordinary numbers. Keep the original hex when the value is an address, mask, hash or colour, or when it must be reproduced exactly.
Evidence gaps: the language behaviours described here come from documented Python, PHP, JavaScript and Excel behaviour. No destination-specific paste tests, assistive-technology tests or online converter evaluations were performed.