Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. i.e. 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?

like image 547
eddydee123 Avatar asked Oct 26 '25 05:10

eddydee123


2 Answers

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

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

or

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

if you wish to remove it.

like image 54
hkN Avatar answered Oct 28 '25 17:10

hkN


The best I could suggest is a condensed version of your approach:

'0'*(len(si:=f'{i:x}')%2)+si
like image 35
Roma_3179904 Avatar answered Oct 28 '25 18:10

Roma_3179904