Python hex() Function — Not a Magic Trick

Python’s built-in hex(integer) function takes one integer argument and returns a hexadecimal string with prefix "0x". If you call hex(x) on a non-integer x, it must define the __index__() method that returns an integer associated to x. Otherwise, it’ll throw a TypeError: object cannot be interpreted as an integer.

Python hex() function

ArgumentintegerAn integer value or object implementing the __index__() method.
Return ValuestringReturns a string of octal numbers, prefixed with "0x".
Input : hex(1)
Output : '0x1'

Input : hex(2)
Output : '0x2'

Input : hex(4)
Output : '0x4'

Input : hex(8) 
Output : '0x8'

Input : hex(10)
Output : '0xa'

Input : hex(11)
Output : '0xb'

Input : hex(256)
Output : '0x100'

Python hex() Video

Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners

Python hex() for Custom Objects

If you call hex(x) on a non-integer or custom object x, it must define the __index__() method that returns an integer associated to x.

class Foo:    
    def __index__(self):
        return 10

f1 = Foo()
print(hex(f1))
# '0xa'

How to Fix “TypeError: ‘float’ object cannot be interpreted as an integer”?

Python’s hex() function can only convert whole numbers from any numeral system (e.g., decimal, binary, octary) to the hexadecimal system. It cannot convert floats to hexadecimal numbers. So, if you pass a float into the hex() function, it’ll throw a TypeError: 'float' object cannot be interpreted as an integer.

>>> hex(11.14)
Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    hex(11.14)
TypeError: 'float' object cannot be interpreted as an integer

To resolve this error, you can round the float to an integer using the built-in round() function or you write your own custom conversion function:

How to Convert a Float to a Hexadecimal Number in Python?

To convert a given float value to a hex value, use the float.hex() function that returns a representation of a floating-point number as a hexadecimal string including a leading 0x and a trailing p and the exponent.

Note that the exponent is given as the power of 2 by which it is scaled—for example, 0x1.11p+3 would be scaled as 1.11 * 2^3 using the exponent 3.

>>> 3.14.hex()
'0x1.91eb851eb851fp+1'
>>> 3.15.hex()
'0x1.9333333333333p+1'

Alternatively, if you need a non-floating point hexadecimal representation similar to most online converters, use the command hex(struct.unpack('<I', struct.pack('<f', f))[0]).

import struct

def float_to_hex(f):
    return hex(struct.unpack('<I', struct.pack('<f', f))[0])


print(float_to_hex(3.14))
print(float_to_hex(88.88))

The output are the octal representations of the float input values:

0x4048f5c3
0x42b1c28f

Sources:

Hex Formatting Subproblems

Let’s consider some formatting variants of the hexadecimal conversion problem converting a number into lowercase/uppercase and with/without prefix. We use the Format Specification Language. You can learn more on this topic in our detailed blog tutorial.

We use three semantically identical variants for each conversion problem.

How to Convert a Number to a Lowercase Hexadecimal With Prefix

>>> '%#x' % 12
'0xc'
>>> f'{12:#x}'
'0xc'
>>> format(12, '#x')
'0xc'

How to Convert a Number to a Lowercase Hexadecimal Without Prefix

>>> '%x' % 12
'c'
>>> f'{12:x}'
'c'
>>> format(12, 'x')
'c'

How to Convert a Number to an Uppercase Hexadecimal With Prefix

>>> '%#X' % 12
'0XC'
>>> f'{12:#X}'
'0XC'
>>> format(12, '#X')
'0XC'

How to Convert a Number to an Uppercase Hexadecimal Without Prefix

>>> '%X' % 12
'C'
>>> f'{12:X}'
'C'
>>> format(12, 'X')
'C'

👉 Recommended Tutorial: Convert Hex String to Hex Number in Python

Summary

Python’s built-in hex(integer) function takes one integer argument and returns a hexadecimal string with prefix "0x".

>>> hex(1)
'0x1'
>>> hex(2)
'0x2'
>>> hex(4)
'0x4'
>>> hex(8)
'0x8'
>>> hex(10)
'0xa'
>>> hex(11)
'0xb'
>>> hex(256)
'0x100'

🧑‍💻 Recommended: Python Integer to Hex [Ultimate Guide]

If you call hex(x) on a non-integer x, it must define the __index__() method that returns an integer associated to x.

class Foo:    
    def __index__(self):
        return 10

f1 = Foo()
print(hex(f1))
# '0xa'

Otherwise, it’ll throw a TypeError: object cannot be interpreted as an integer.

Where to Go From Here?

Enough theory. Let’s get some practice!

Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

You build high-value coding skills by working on practical coding projects!

Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!