Python hex to int

Python hex to int

In the world of programming, there are a lot of conversions of data types that programmers have to make that best suit their problem statement. One of these conversions is a hexadecimal string to integer and vice-versa. The hexadecimal number is one such number system that is highly used in storing memory addresses, IP addresses, and more. And integers in python are used in pretty much every program of any programming language.

Hexadecimal values have a base of 16. In Python, hexadecimal strings are prefixed with 0x. Integer values are of many types, they can be whole numbers, positive or negative numbers, floating-point numbers,etc.

In this tutorial, we will see some methods to convert hex String to int in Python.

Use of int() Function to convert hex to int in Python

int() function is one of the most common functions to convert hex to int in python. This function helps us to convert a specific number in its present base to a decimal value. While using this function, the base of the number that has to be converted must be mentioned.

This function also helps in converting alphabets related to the hexadecimal system that are from A to F.

Example:

Output:

Initial String: F
Conversion of hexadecimal string : 15

Also, note that str() function is used to concatenate the converted integer with the given string.

To convert a hexadecimal number to a normal integer using the int() function, the following is the way to do it:

Output:

296

Note that 0x is used as a prefix of the hexadecimal number that has to be converted i.e 24. 0x prefix denotes the number given by the user is a hexadecimal number. Here, it was not necessary to write the 0x prefix to denote the hexadecimal number as the base of the number is also mentioned.

However, if the 0x prefix is mentioned and the base is not defined, there will be an ValueError: invalid literal for int() with base 10.

Output:

ValueError Traceback (most recent call last)
in
—-> 1 int(‘0x128’)
ValueError: invalid literal for int() with base 10: ‘0x128’

However you can use base as 0 if you have 0x as prefix in hexadecimal string.

Output:

296

Use of ast.literal_eval() Function to convert hex to int in Python

ast stands for Abstract Syntax Trees which an in-built python module used for finding out the current grammar in a very systematic manner.

The ast.literal_eval() function helps in evaluating python expressions and python structures like string, floats, integers, tuples, lists, dictionaries, etc.

Example:

Output:

Initial hexadecimal string: 0x128
Conversion of hexadecimal string: 296

Here, the literal_eval() function is applied to the initial string. After that, the literal_eval() function finds the base of that string and converts the number to its integer value. Finally, both initial values and the hexadecimal values are printed.

Use of Dictionary to convert hex to int in Python

Dictionary in python is a collection of items that have their individual values. To get a value of a particular item, that item is called with its name.

In this method, we will make a dictionary consisting of values that will help us in the conversion of hexadecimal string to an integer.

Example:

Output:

Enter initial hexadecimal string: D3
Conversion of hexadecimal string : 211

Note that in this method, we have taken input from the user and we have used the upper() function to convert the input to upper-case. After that, we have initialized the integer value to 0 and used a for loop for the conversion. The len() function used in the above code is used to get the number of characters in the input string. Finally, we print the converted value.

That’s all about Python hex to int.

Related Posts

  • Detect keypress in Python
    12 June

    Detect keypress in Python

    Table of ContentsUsing the keyboard module to detect keypress in PythonUsing the pynput module to detect keypress in PythonUsing the msvcrt module to detect keypress in Python Python allows us to work with user input in its programs. We can also work with hardware devices in Python. In this article, we will discuss how to […]

  • Copy a dictionary in Python
    12 June

    7 ways to copy a dictionary in python

    Table of ContentsUsing the copy() function to copy a dictionary in PythonUsing the deepcopy() function to copy a dictionary in PythonUsing the dict() function to copy a dictionary in PythonUsing the unpack operator ** to copy a dictionary in PythonUsing the update() function to copy a dictionary in PythonUsing the dictionary comprehension method to copy […]

  • Escape quotes in Python
    11 June

    Escape quotes in Python

    Table of ContentsUsing \ to escape quotes in PythonUsing \ with replace() to escape quotes in PythonUsing json.dumps to escape quotes in PythonUsing triple single or double quotes to escape quotes in pythonUse r to include \ and quotes in String 💡 Outline You can use \ to escape quotes in Python. If you want […]

  • Sleep for milliseconds in python
    31 May

    How to sleep for milliseconds(ms) in Python

    Table of ContentsUse time.sleep() function to make the program sleep for millisecondsUse threading.Timer() function to make the program sleep for milliseconds 💡 Outline You can use time.sleep() method to sleep for milliseconds in Python. If you want to delay python program by 500 ms, then you need to pass 0.5 as parameter to sleep method. […]

  • Convert unix timestamp to datetime in Python
    21 May

    Convert Unix timestamp to DateTime in python

    Table of ContentsUsing fromtimestamp() FunctionUsing strftime() FunctionUsing to_datetime() Function A UNIX timestamp is defined as the several numbers of seconds between a particular date and the Epoch i.e January 1, 1970 at UTC. In this tutorial, we will see some methods by which we can convert a UNIX timestamp to DateTime in Python. Using fromtimestamp() […]

  • Python round to 2 decimal places
    21 May

    How to round to 2 decimals in Python

    Table of ContentsUsing the round() functionUsing the format() functionUsing the % formattingUsing the f-stringsUsing the math.ceil() and math.floor() functions In Python, we deal with integers, floating values, and even imaginary numbers. Float numbers are used to represent the real numbers with integers and decimal parts. Python represents such numbers with 64-bit precision giving it a […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.