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?
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.
The best I could suggest is a condensed version of your approach:
'0'*(len(si:=f'{i:x}')%2)+si
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With