Convert hexadecimal values in Python

How Python converts hex strings to integers, formats numbers as hex, and handles bytes and text, with the tradeoffs to check before sharing hex output.

Hexadecimal in Python is a way of writing a value, not a separate kind of value. Converting between hex and decimal changes only the notation of an integer. Converting text to hex is different: it exposes the encoded bytes behind the text, so the result depends on which encoding was used. This review covers what each conversion changes, where information can be lost, and when hex output is less useful than plain text or decimal.

Is hex conversion the right choice for your use?

Hex is a good fit when you need an exact, compact, reversible view of bit patterns or raw bytes. Typical cases are checksums, color codes, memory addresses, protocol dumps and binary file inspection. The main tradeoff is that hex shows structure, not meaning. A reader cannot tell from a hex string whether it holds a number, encoded text or packed binary data. It also does not record width, sign convention, byte order or text encoding unless you state them separately. If people need to understand a quantity or read a message, use decimal or the decoded text instead, or provide it alongside the hex.

  • Hex suits: byte-level debugging, hashes and digests, bit masks and flags, color values, and data that must round-trip exactly.
  • Decimal or plain text suits: quantities people read or compare, user-facing messages, search-indexed content, and any setting where readers do not need the underlying bytes.

What converting actually changes

For integers, hex is purely a presentation choice. The literal 0xff in source code creates the same int object as 255. Python stores the number, not the notation, so no hex-ness persists after parsing. Output functions build a new string each time you ask for a hex representation.

>>> 0xff == 255
True
>>> type(0xff)
<class 'int'>
>>> hex(255)
'0xff'

Turning a hex string into an int

Use int() with base 16 to parse a hex string as a decimal-valued integer. Upper and lower case digits are both accepted. With base 16, an optional 0x or 0X prefix is also allowed, and surrounding whitespace is ignored. Base 0 tells Python to infer the base from the prefix, so it requires the prefix and rejects bare hex digits. Any character outside 0-9 and a-f raises ValueError, which makes input validation straightforward.

>>> int('ff', 16)
255
>>> int('0xFF', 16)
255
>>> int('  ff  ', 16)
255
>>> int('0xff', 0)
255
>>> int('ff', 0)
ValueError: invalid literal for int() with base 0: 'ff'
>>> int('fg', 16)
ValueError: invalid literal for int() with base 16: 'fg'

Formatting an int as hex

hex() always returns lowercase output with a 0x prefix. For other output, use format() or an f-string with the x or X format type. These give you control over the prefix, the case and zero-padding. When the # flag is used, the width includes the two prefix characters.

Expression | Result
hex(255) | '0xff'
format(255, 'x') | 'ff'
format(255, 'X') | 'FF'
format(255, '#x') | '0xff'
format(255, '#X') | '0XFF'
f'{10:02x}' | '0a'
f'{255:#06x}' | '0x00ff'

Two details are easy to lose. First, leading zeros do not survive a round trip through int: '00ff' parses to 255, and formatting it back gives 'ff' unless you request a width again. If the width carries meaning, as with fixed-size fields or byte values, store or document it. Second, Python formats negative integers with a minus sign, not in two's complement. For a fixed-width two's complement form, mask the value or use int.to_bytes with signed=True, and use int.from_bytes to read it back.

>>> hex(-255)
'-0xff'
>>> format(-1 & 0xFF, '02x')
'ff'
>>> (-1).to_bytes(2, 'big', signed=True).hex()
'ffff'
>>> int.from_bytes(bytes.fromhex('ffff'), 'big', signed=True)
-1

Byte order is the one sense in which hex values get reversed. The same bytes produce different integers depending on whether they are read as big-endian or little-endian. A hex string does not record which order was intended.

>>> int.from_bytes(bytes.fromhex('0100'), 'big')
256
>>> int.from_bytes(bytes.fromhex('0100'), 'little')
1

Text and bytes: where meaning can shift

A str has no hex form of its own. To get one, you encode it to bytes and then call .hex(). The encoding choice changes the output: the same word gives different hex under UTF-8 and Latin-1. A character's code point, from ord(), is also different from its UTF-8 bytes. Visually identical text can produce different hex too. An accented letter typed as one precomposed character encodes differently from a plain letter followed by a combining accent. A single emoji can span several bytes and sometimes several code points. Before comparing or decoding hex taken from text, confirm the encoding and the Unicode normalization form.

>>> 'café'.encode('utf-8').hex()
'636166c3a9'
>>> 'café'.encode('latin-1').hex()
'636166e9'
>>> hex(ord('é'))
'0xe9'
>>> 'cafe\u0301'.encode('utf-8').hex()   # e + combining acute accent
'63616665cc81'
>>> '👍'.encode('utf-8').hex()
'f09f918d'

To go the other way, bytes.fromhex() parses a hex string into bytes. It skips ASCII whitespace between byte pairs, and it rejects a 0x prefix or an odd number of digits. bytes.hex() accepts an optional separator for readable grouping, a feature added in Python 3.8. Decode the bytes with the original encoding to recover the text.

>>> bytes.fromhex('48 65 6c 6c 6f')
b'Hello'
>>> bytes.fromhex('48656c6c6f').decode('utf-8')
'Hello'
>>> b'Hello'.hex(' ')
'48 65 6c 6c 6f'
>>> bytes.fromhex('0x48')
ValueError: non-hexadecimal number found in fromhex() arg at position 1

Floating-point values

Floats cannot go through int() or hex(). float.hex() and float.fromhex() give an exact hexadecimal representation of the binary value, which is useful for reproducing floats without decimal rounding. This notation is unfamiliar to most readers and does not belong in user-facing output.

>>> (0.1).hex()
'0x1.999999999999ap-4'
>>> float.fromhex('0x1.8p1')
3.0

Will hex output stay usable after copying or sharing?

Hex output from Python is plain ASCII, so the characters themselves are unlikely to be altered by copy and paste. The risk lies in how the destination interprets them. A receiving tool may expect or reject a 0x prefix. It may treat case as significant, or treat a digits-only string as a number and drop leading zeros or reformat it. Some strings that mix digits with e can look like scientific notation. No destination-specific testing was supplied for this review. Check the actual import or display path you plan to use, and quote or type the field as text where the tool allows it.

For human readers, long unbroken hex strings are hard to proofread and compare. Grouping bytes with a separator helps, but it changes the string, so the receiver must know to strip the separators before parsing. No evidence was supplied about how specific screen readers or other assistive technologies announce hex strings, and this review makes no claim about them. If the content carries meaning for a person, such as a value, a message or a color, include a plain-text equivalent: the decimal number, the decoded text or a description. Search tools generally match the characters as written, so hex-encoded text will not be found by searching for the words it encodes.

  • State the format alongside the data: prefix or not, case, width, signedness, byte order, and the text encoding if the hex came from text.
  • Keep fixed widths explicit with format specs such as 02x so leading zeros are not lost.
  • Normalize Unicode text before encoding if the hex values will be compared.
  • Round-trip a sample through the destination and back into Python before relying on it.
  • Provide decimal or decoded text wherever a person needs the meaning rather than the bytes.

Gaps and scope

The behavior described here comes from Python's built-in int, hex, format, bytes and float functions. The examples show the expected interpreter output, but they were not run in a recorded test for this article. Exact error message wording can vary between Python versions, and the bytes.hex() separator requires Python 3.8 or later. No measurements, third-party tool tests or assistive technology tests were available. Treat claims about destinations as items to check, not confirmed results.