3

Is there a reasonably simple way to convert from a hex integer to a hex string in python? For example, I have 0xa1b2c3 and I want "0xa1b2c3". If I use str(), it automatically gets converted to base 10, and then I can't convert it back because it's a string at that point.

2 Answers 2

5

Why not just do hex()?

>>> testNum = 0xa1b2c3
>>> hex(testNum)
    '0xa1b2c3'
>>> test = hex(testNum)
>>> isinstance(test, str)
    True

hex returns a string representation. See help(hex)

hex(...)
    hex(number) -> string

    Return the hexadecimal representation of an integer or long integer.
Sign up to request clarification or add additional context in comments.

Comments

3

Use hex:

>>> x = 0xa1b2c3
>>> hex(x)
'0xa1b2c3'

or string formatting:

>>> "{:#x}".format(x)
'0xa1b2c3'

or format:

>>> format(x, '#x')
'0xa1b2c3'

2 Comments

Use the format() function instead; format(x, '#x'). No need to have the overhead of the string format parsing too.
Thanks. It seems like you both answered the same thing at the same time, so I'm accepting his answer because he has a lot less reputation points than you. Cheers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.