hex()

The built-in hex() function converts a given integer into its hexadecimal representation. The output is a string prefixed with 0x:

Python
>>> hex(42)
'0x2a'

hex() Signature

Python Syntax
hex(x)

Arguments

Argument Description
x An integer value or an object defining an .__index__() method that returns an integer

Return Value

  • Returns a string holding the hexadecimal representation of the input integer, prefixed with 0x.

hex() Examples

With a positive integer as an argument:

Python
>>> hex(255)
'0xff'

With a negative integer as an argument:

Python
>>> hex(-42)
'-0x2a'

With an object of a class with a .__index__() method:

Python
>>> class Number:
...     def __init__(self, value):
...         self.value = value
...     def __index__(self):
...         return self.value
...

>>> number = Number(10)
>>> hex(number)
'0xa'

hex() Common Use Cases

The most common use cases for the hex() function include:

  • Converting integer values to hexadecimal strings for use in digital systems, such as color codes in web development.
  • Debugging or logging in systems that require hexadecimal notation.
  • Preparing data for protocols or file formats that use hexadecimal representation.

hex() Real-World Example

Let’s say you need to convert a list of decimal RGB values into their hexadecimal color code equivalents for use in web design.

Python
>>> rgb_values = [255, 165, 0]
>>> hex_colors = [hex(value)[2:] for value in rgb_values]  # Strip the '0x' prefix
>>> hex_color_code = '#' + ''.join(hex_colors)
>>> hex_color_code
'#ffa500'

In this example, the hex() function is used to convert each RGB component to its hexadecimal equivalent, allowing you to generate a valid hex color code for web use.

Tutorial

Python's Built-in Functions: A Complete Exploration

In this tutorial, you'll learn the basics of working with Python's numerous built-in functions. You'll explore how to use these predefined functions to perform common tasks and operations, such as mathematical calculations, data type conversions, and string manipulations.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 21, 2024 • Reviewed by Dan Bader