pythonstringinthexascii

Why Does Hex() Function returns a string instead an int hex?


I dont know why Hex function returns a string like '0x41' instead 0x41

enter image description here

I need to convert an ASCII value into a hex. But i want in 0x INT format, not into a '0x' string.

ascii = 360
hexstring = hex(ascii)
hexstring += 0x41  # i cant do this because hexstring is a string not a int hex

How i can get a int hex?? thanks


Solution

  • There is no int hex object. There is only an alternative syntax to create integers:

    >>> 0x41
    65
    

    You could have used 0o101 too, to get the same value. Or use 0b1000001 to specify it in binary; they are all the exact same numeric value to Python; they are all just different forms to specify an integer value in your code.

    Simply keep ascii as an integer and sum your hex notation values with that:

    >>> ascii = 360
    >>> ascii += 0x41
    >>> ascii
    425
    

    hex() produces a string that can be interpreted by a Python program in the same manner, and is usually used when debugging code or quick presentation output (but you should use format(number, 'x') if you want to produce end-user output without the 0x prefix). It is not needed to work with integers.