Search code examples
pythonrecursiondecimalhex

python recursively convert decimal to hex


How would you recursively or iteratively change a decimal to hexadecimal?

I wrote a sample program that does not really work:

def ChangeHex(n):
    if (n < 0):
        print(0)
    elif (n<=1):
        print(n)
    else:
        ChangeHex(n / 16)
        if (n == 15):
            print("F")
        if (n == 14):
            print("E")
        if (n == 13):
            print("D")
        if (n == 12):
            print("C")
        if (n == 11):
            print("B")
        if (n == 10):
            print("A")
        n % 16

How would I make it work properly? I know there is a built in function but I want to do it this way.


Solution

  • # Converts a decimal number to hexadecimal.
    # Executes a zero-fill for up to six digits.
    # This is used for correct conversion back
    # to the instruction format. See zero_fill().
    # @param  dec  Decimal representation of instruction
    # @return  Zero-filled hexadecimal instruction.
    def convert(dec):
    # BEGIN convert()
        hex = "%X" % dec
        return zero_fill(hex, 6)
    # END convert()
    
    # Prepends zeros until the specified
    # length is reached. Works recursively.
    # @param  n  Number to fill
    # @param  length  Length to reach
    # @return  Zero-filled number
    def zero_fill(n, length):
    # BEGIN zero_fill()
        # Check if length requirement is met
        if len(n) != length:
            # Requirement not met, run function again with
            # n having one prepended zero.
            return zero_fill('0'+n, length)
        else:
            # Requirement met, return n.
            return n
    # END zero_fill()