Search code examples
pythonhex

Converting hex string to hex int in python


Lets say i have a txt file called: Msg.txt

I read this with

Read_msg = open("Msg.txt", "r")

Hex =  Read_msg.readline()

This provides me with a hex string called '0xfff'.

Problem is that the system i work with needs a variable that is hex but also int.

If i make a variable in python that is called:

Hex = 0xfff

Then it is fine, but i need to be able to extract this data from a txt or excel. (if you do type() on this variable then it ses int even if it is hex.)

I tried converting the string with:

Hex = int(Hex, 16)

Hex = hex(Hex)

But this makes it into a string again. Is what i'm looking for even possible?


Solution

  • As you can see in the documentation hex() function returns a string:

    hex(x) Convert an integer number to a lowercase hexadecimal string prefixed with “0x”.

    If you simply assign hex value to a variable it becomes just a regular integer:

    >>> a = 0xfff
    >>> a
    4095
    

    You can use hex() function to then see that integer in hex format again:

    >>> hex(a)
    '0xfff'
    

    The data itself is stored in binary so there is no such a thing as hex int or decimal integer, because (obviously) they are all actually binary.