Input a number in Hexadecimal format in Python

Python | Hexadecimal Input: In this tutorial, we will learn how to input a number in Hexadecimal format in Python programming language? Submitted by IncludeHelp, on April 27, 2020

Function to take input in hexadecimal (or, convert hexadecimal to an integer)

Python's int() function with the base value 16 is used to take input in a hexadecimal format or to convert a given hexadecimal value to an integer (decimal) value.

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

Input a number in Hexadecimal format

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...

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.