Search code examples
pythonstringhexbitxor

xor with leading zero issue in python


I want to xor two hex-format strings in python, like '45' and '4e'. But how do I keep the leading zero if the result is in [0x00, 0x0f]?

hex(int('45', 16) ^ int('4e', 16))

gives '0xb', while I'm expecting '0x0b'.

Thanks in advance.


Solution

  • The easiest method is to use str.format():

    >>> '0x{:02x}'.format(0xb)
    '0x0b'