The easiest way to convert the number into base 4 is to first convert the number into hexadecimal (base 16) using Python's built-in facilities, then map each hex digit to two base-4 digits. Since each base-4 digit represents 2 bits, and each base-16 digit represents 4 bits, this is an exact mapping.
DIGIT_MAP = {"0": "00", "1": "01", "2": "02", "3": "03",
"4": "10", "5": "11", "6": "12", "7": "13",
"8": "20", "9": "21", "a": "22", "b": "23",
"c": "30", "d": "31", "e": "32", "f": "33"}
def decimal_to_base4(num):
return "".join(DIGIT_MAP[c] for c in "%x" % num).lstrip("0") or "0"
How it works:
First, we convert the incoming number to hex using "%x" % num
. We could also use hex()
, but this adds a leading 0x
to the conversion, which we'd then have to strip off (i.e. this could also be written as hex(num)[2:]
).
We loop over the result, setting c
to each character in the hex version of the number.
For each iteration in the loop, we yield DIGIT_MAP[c]
, which is the two base-4 digits that are equivalent to the given base-16 digit.
We join the resulting strings with the null string, resulting in a single string with all the numbers in order.
The result may have a leading zero since any hex digit less than 4
results in a base-4 digit-pair starting with 0. So we strip this off using .lstrip("0")
.
But if the number was zero to begin with, the .lstrip()
takes off the entire digit, resulting in an empty string, ""
. The or "0"
restores the "0" in the case of an empty string.