Sling Academy
Home/Python/How to Convert a Number to a Hex String in Python

How to Convert a Number to a Hex String in Python

Last updated: June 03, 2023

This pithy article shows you how to turn a number (integer, float) into a hexadecimal value in Python.

Convert an integer to a hex value

You can use the hex() function to convert a given integer to a hex string that starts with the prefix 0x.

Example:

my_int = 2023
my_hex = hex(my_int)
print(my_hex)

Output:

0x7e7

Using the format() function with the x specifier is an alternative solution. However, it returns a hex string without the prefix 0x. You can simply add this prefix with string concatenation if needed.

Example:

# convert 2023 to hex without prefix
my_hex = format(2023, 'x')
# add prefix
my_hex = '0x' + my_hex
print(my_hex)

Output:

0x7e7

Convert a float to a hex string

In Python, in order to convert a float number to a hex string, the easiest and most convenient way is to use the float.hex() method. The resulting hex string has the form 0xh.hhhhp+e, where h.hhhh is the hexadecimal fraction, and e is the exponent in decimal.

Example:

my_float = 9.999
my_hex = my_float.hex()
print(my_hex)

Output:

0x1.3ff7ced916873p+3

That’s it. Happy coding & have a nice day. Goodbye!

Next Article: Python: 2 Ways to Convert an Integer to Binary

Previous Article: Python: 4 Ways to Round a Number

Series: Python – Numbers & Math Tutorials

Python

You May Also Like

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots