How to Convert Hexadecimal to Decimal in Python
Table of Contents
In programming, you oftentimes work with numbers in different formats, such as hexadecimal and decimal.
This is because different formats are used for different scenarios. Hexadecimal is used in things like colors in CSS, IP and memory addresses.
Decimal is used for mathematical operations, such as adding, subtracting, multiplying, and dividing.
In this post, we'll learn how to convert a hexadecimal number to a decimal number in Python.
Using int()
The recommended way to convert a hexadecimal number to a decimal number is to use the int()
function.
This function will typecast your hexadecimal string to its decimal equivalent as an integer.
To do this, you just need to pass it your hexadecimal string and the base, in this case, 16
.
PYTHONhex = "0xFF"
dec = int(hex, 16)
print(dec)
BASH255
Using ast
Another way you can convert a hexadecimal number to a decimal number is to use the ast
module.
This module provides a literal_eval
function that will take a string and evaluates it.
When you pass this function a hexadecimal string, it will return the decimal equivalent.
Let's look at an example:
PYTHONimport ast
hex = "0xFF"
dec = ast.literal_eval(hex)
print(dec)
BASH255
Conclusion
In this post, we looked at the two best ways to convert a hexadecimal number to a decimal number.
You can either use the built-in int()
function or import the ast
module to accomplish the task.
Hope this has been useful to you! Thanks for reading!
- Getting Started with Svelte
- Getting Started with Electron
- How to build a Discord bot using TypeScript
- How to deploy a Node app using Docker
- Learn how to use v-model with a custom Vue component
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- How To Create a Modal Popup Box with CSS and JavaScript