SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Y Daniel Lang
Chapter:
.loops
Exercise:
Programming Excercises
Question:45 | ISBN:978013274719 | Edition: 6

Question

(Decimal to hex) Write a program that prompts the user to enter a decimal integer and displays its corresponding hexadecimal value.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Decimal to Hex decimal conversion Program code:


#The following method is used to convert
#decimal integer to hexadecimal 
def decToHexConversion(n):
  hex_digits = []
  while n > 0:
    rem = n % 16
    hex_digits.append(rem)
    n //= 16

  hex_value = "".join(["0" + hex(d)[2:] for d in hex_digits])
  return hex_value

#The main method is used to  prompts the user to enter a decimal integer 
#call the method, decToHexConversion and display result
def main():

  decimal_integer = int(input("Enter a decimal integer: "))
  hexadecimal_value = decToHexConversion(decimal_integer)
  print("The hexadecimal value of {} is {}".format(decimal_integer, hexadecimal_value))
if __name__ == "__main__":
  main()

Executed Output:

Enter a decimal integer: 5678
The hexadecimal value of 5678 is 0e020601

 

0 0

Discussions

Post the discussion to improve the above solution.