简体   繁体   中英

Python convert int to hex string with even number of characters

I want to convert an arbitrary integer into a hex string with an even number of hex characters. ie each consecutive pair of characters in the string represent a byte of the integer (in big-endian).

So the hex string should start with a zero character iff needed in order to make an even number of characters.

Since the integer is arbitrary, I do not know the length of the hex string in advance. There are lots of other questions about how to add leading zeros, but they all assume I know the length of the desired hex string. I did not find a duplicate of this specific question anywhere.

I'm happy to use Python 3.8.

I've tried the following:

i = 1000  # required output is '03e8'. i could be much larger or smaller

f"{i:02x}"             # '3e8'
f"{i:0>2x}"            # '3e8'
f"{i:x}".zfill(2)      # '3e8' 
"0" + f"{i:x}" if len(f"{i:x}") % 2 else f"{i:x}"  # '03e8' as required, but really?!

Isn't there a concise way to do this using format specifiers?

you could do if you wish to keep the 0x at the beginning of the string:

def even_hex(my_int):
str = hex(my_int)
if len(str) % 2 == 1:
    str = str.replace('0x', '0x0')
return str

or

def even_hex_without_ox(my_int):
str = hex(str)
if len(str) % 2 == 1:
    str = str.replace('0x', '0')
else:
    str = str.replace('0x', '')
return str

if you wish to remove it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM