Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

Tuesday, May 7, 2013

Decimal to Hexadecimal


Problem: Convert the given decimal whole number to hexadecimal.

Example:


decimal_to_hex(32)
20

decimal_to_hex(31)
1F

decimal_to_hex(6543)
198F


Solution in Python:

def decimal_to_hex(n):
    """
    Author: Mayur P Srivastava
    """

    if n == 0:
        return "0";

    hex_str = "";

    while n > 0:
        c = n % 16
        n = n // 16
        if c > 9:
            c = chr(65 + c - 10)
        else:
            c = str(c)
        hex_str = c + hex_str

    return hex_str


Concepts Learned: Single loops, number systems

No comments:

Post a Comment