In: Computer Science
The hexademical number system uses base 16 with digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F. Hexadecimal is often used in computer systems programming. Write a Python program, in a file called convertHex.py, to request a decimal number from the user and output the hexadecimal value. To compute the hexadecimal value we have to find the hexadecimal digits hn, hn-1, hn-2, ..., h2, h1, and h0, such that
d = hn x 16n + hn-1 x 16n-1 + hn-2 x 16n-2 + ... + h2 x 162 + h1 x 161 + h0 x 160
These hexadecimal digits can be found by successively dividing d by 16 until the quotient is 0; the remainders are h0, h1, ..., hn-1, hn.
For example, if d=589:
So 589 in decimal is 24D in hexadecimal.
Your program should include the following functions:
Sample output:
Enter decimal value: 589 589 is equal to 24D in hexadecimal
Below is your code: -
def main():
num = int(input("Enter decimal value: "))
print(num,"is equal to",decToHex(num), "in hexadecimal")
def decToHex(dec_value):
val = str()
while dec_value > 0:
hexV=dec_value%16
dec_value=dec_value//16
val = getHexChar(hexV) + val
return val
def getHexChar(dec_digit):
if dec_digit < 10:
return str(dec_digit)
if dec_digit == 10:
return "A"
if dec_digit == 11:
return "B"
if dec_digit == 12:
return "C"
if dec_digit == 13:
return "D"
if dec_digit == 14:
return "E"
if dec_digit == 15:
return "F"
main()
Output