How to convert decimal to hex in the following format (at least two digits, zero-padded, without an 0x prefix)?
Input: 255 Output:ff
Input: 2 Output: 02
I tried hex(int)[2:] but it seems that it displays the first example but not the second one.
Use the
format()function with a'02x'format.The
02part tellsformat()to use at least 2 digits and to use zeros to pad it to length,xmeans lower-case hexadecimal.The Format Specification Mini Language also gives you
Xfor uppercase hex output, and you can prefix the field width with#to include a0xor0Xprefix (depending on wether you usedxorXas the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters: