Converting Decimal to Hexadecimal Without the Hex() Function in Python

Converting Decimal to Hexadecimal Without the Hex() Function in Python

ECX 30 Days of Code

Day 4

Decimal to Hexadecimal.

Task

Without using the inbuilt hex() function, write a function that takes an integer as input, and prints out its conversion to hexadecimal as output.

Discussion

To convert decimal (base 10) to hexadecimal (base 16), we can make use of the long division method. We would continuously divide the number we are given until it becomes equal to zero. As we divide, we take note of the remainders. When we are done, we have the last remainder to be our most significant hexadecimal digit and the first remainder as our least significant hexadecimal digit (i.e., we arrange the remainders from bottom to top; in other words, the last remainder is the first hexadecimal digit (leftmost) and the first remainder is the last hexadecimal value (rightmost)).

image.png

My Approach

This is the full code. I would explain in bit throughout this article.

def dec_to_hex(dec_num):
    """This convert a decimal number to a hexadecimal."""

    # Print the decimal value.
    print('Decimal:', dec_num)

    # Variable to store the hexadecimal output.
    hex_num = ''

    if dec_num == 0:
        print(dec_num)

    # While loop for division of dec_num by 16 until it is equal to zero.
    while dec_num > 0:

        # Remainder of divisions by 16.
        remainder = dec_num % 16

        # 10, 11, 12, 13, 14, 15 are A, B, C, D, E, and F respectively in hexadecimal.
        if remainder == 10:
            remainder = 'A'
        elif remainder == 11:
            remainder = 'B'
        elif remainder == 12:
            remainder = 'C'
        elif remainder == 13:
            remainder = 'D'
        elif remainder == 14:
            remainder = 'E'
        elif remainder == 15:
            remainder = 'F'

        # This stores the remainders in reverse order to give us our hexadecimal output.
        hex_num = str(remainder) + hex_num

        # We assign dec_num to have the value of the quotient of the division, before another division occurs again.
        dec_num = dec_num // 16

    # Print the hexadecimal value.
    print('Hexadecimal:', hex_num)


# User input
print(' Decimal to Hexadecimal '.center(40, '*'))
user_input = int(input('Enter the decimal number you want to convert to hexadecimal: '))

# Function call.
dec_to_hex(user_input)

First, we define our function, dec_to_hex(), and we print the decimal number inputted by the user. We then create a variable, hex, and assign it to an empty string; it would be used for storing the value of the hexadecimal number. We then check if the user input is zero; if so, we print zero as our answer.

def dec_to_hex(dec_num):
    """This convert a decimal number to a hexadecimal."""

    print('Decimal:', dec_num)

    hex_num = ''

    if dec_num == 0:
        print(dec_num)

Next, we would continually divide the decimal number inputted by the user, taking note of the remainder, which we would store in the variable, hex_num, in reverse order using hex_num = str(remainder) + hex_num. We would use the if and elif statements to assign the remainders from 10 to 15 to have values A to E respectively.

while dec_num > 0:

    remainder = dec_num % 16

    if remainder == 10:
        remainder = 'A'
    elif remainder == 11:
        remainder = 'B'
    elif remainder == 12:
        remainder = 'C'
    elif remainder == 13:
        remainder = 'D'
    elif remainder == 14:
        remainder = 'E'
    elif remainder == 15:
        remainder = 'F'

    hex_num = str(remainder) + hex_num

    dec_num = dec_num // 16

We then print out our hexadecimal value. The user is asked to input the values he wants to change to hexadecimal and the dec_to_hex() function is called.

    print('Hexadecimal:', hex_num)


print(' Decimal to Hexadecimal '.center(40, '*'))
user_input = int(input('Enter the decimal number you want to convert to hexadecimal: '))

dec_to_hex(user_input)

Output

If we choose to convert 1023 (decimal), we would get 3FF (hexadecimal) as our output.

******** Decimal to Hexadecimal ********
Enter the decimal number you want to convert to hexadecimal: 1023
Decimal: 1023
Hexadecimal: 3FF

Run the code on Replit