Input a number in Hexadecimal format in Python

Python | Hexadecimal Input: Here, we are going to learn how to input a number in Hexadecimal format in Python programming language?
Submitted by IncludeHelp, on April 27, 2020

Syntax to convert hexadecimal value to an integer (decimal format),

    int(hex_value, 16)

Here,

  • hex_value should contain the valid hexadecimal value
  • 16 is the base value of the hexadecimal number system

Note: hex_value must contain only hexadecimal digits (0, 1, 2, 3 ,4 ,5 ,6, 7, 8, 9, A/a, B/b, C/c, D/d, E/e, F/F), if it contains other than these digits a "ValueError" will return.

Program to convert given hexadecimal value to integer (decimal)

# function to convert given hexadecimal Value
# to an integer (decimal number)
def HexToDec(value):
  try:
    return int(value, 16)
  except ValueError:
    return "Invalid Hexadecimal Value"

# Main code
input1 = "1235A"
input2 = "6ABF"
input3 = "6AG09"

print(input1, "as decimal: ", HexToDec(input1))
print(input2, "as decimal: ", HexToDec(input2))
print(input3, "as decimal: ", HexToDec(input3))

Output

1235A as decimal:  74586
6ABF as decimal:  27327
6AG09 as decimal:  Invalid Hexadecimal Value

Now, we are going to implement the program – that will take input the number as a hexadecimal number and printing it in the decimal format.

Program to input a number in hexadecimal format

# input number in hexadecimal format and 
# converting it into decimal format

try:
  num = int(input("Input hexadecimal value: "), 16)
  print("num (decimal format):", num)
  print("num (hexadecimal format):", hex(num))  
except ValueError:
  print("Please input only hexadecimal value...")

Output

RUN 1:
Input hexadecimal value: 123
num (decimal format): 291
num (hexadecimal format): 0x123

RUN 2:
Input hexadecimal value: 6ABF12
num (decimal format): 6995730
num (hexadecimal format): 0x6abf12

RUN 3:
Input hexadecimal value: 1234ABCFDEF
num (decimal format): 1251089382895
num (hexadecimal format): 0x1234abcfdef

RUN 4:
Input hexadecimal value: 65afcd
num (decimal format): 6664141
num (hexadecimal format): 0x65afcd

RUN 5:
Input hexadecimal value: 123AFG
Please input only hexadecimal value...





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.