How do I treat hex text as a string?

I have a hexadecimal number such as 0x61cc1000

and I want to inject them into a function that only accepts a string. I want to treat hex numbers as strings without any modification.

If I use a function str()

, it converts it to int

and then treats it as a string. But I want to keep the original hex value.

+3


source to share


3 answers


Your problem is that you are using str

:

>>> str(0x61cc1000)
'1640763392'  # int value of the hex number as a string

      

This is because the first 0x61cc1000 is evaluated as int

then str

executed in the above int

.

You want to do:

"{0:x}".format(0x61cc1000)

      



or

'{:#x}'.format(0x61cc1000)

      

As already stated in another answer, you can simply:

>>> hex(0x61cc1000)
'0x61cc1000'

      

See 6.1.3.1. See Mini-Language Specification Format for more details.

+4


source


If you need the hexadecimal representation of any integer, just pass it inline hex

.



>>> n = 0x61cc1000
>>> n
1640763392
>>> hex(n)
'0x61cc1000'

      

+2


source


If you want to have 0x at the beginning, you can use the format #x

like this:

'{:#x}'.format(74954)

      

+1


source







All Articles