This post contains a total of 20+ Hand-Picked Python Hexadecimal to Decimal converter examples with Source Code. All the Hexadecimal to decimal converters are made using Python Programming Language.
You can use the source code of these programs for your own personal or educational use with credits to the original owner.
Related Posts
Click a Code to Copy it.
1. By Issa
Made by Issa. Simple Python program to convert hexadecimal number into decimal. ( Source )
n=input()
for i in n :
assert i in ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","10"], "Hexadecimal only."
hex={"0":0,"1":1,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7,"8":8,"9":9,"A":10,"B":11,"C":12,"D":13,"E":14,"F":15,"10":16}
s=[]
p=len(n) - 1
if n in hex :
print(hex[n])
else :
for i in range(len(n)) :
try :
s.append(int(n[i])*(16**p))
except :
s.append(hex[n[i]]*(16**p))
p -= 1
print(sum(s))
2. By Hugo Chan
Made by Hugo Chan. Write letters in UPPERCASE # input example : AE14 –> 44564. ( Source )
blacklist_char = "GHIJKLMNOPQRSTUVWXYZ"
hex_values = {
"0": 0,
"1": 1,
"2": 2,
"3": 3,
"4": 4,
"5": 5,
"6": 6,
"7": 7,
"8": 8,
"9": 9,
"A": 10,
"B": 11,
"C": 12,
"D": 13,
"E": 14,
"F": 15
}
try:
hex_input = str(input())
for char in hex_input:
if char in blacklist_char or char.islower():
raise
except:
print("Your input must contains letters[A-F] or numbers[0-9].")
else:
hex_list = []
for i in hex_input:
hex_list.append(i)
n = len(hex_list) - 1
decimal = 0
for j in hex_list:
decimal += hex_values[j] * (16 ** n)
n -= 1
print("Hexadecimal input :", hex_input)
print("Decimal Form :", decimal)
print("\n\n\nPlease, upvote if you like :)")
3. By Jose Federico Gomez
Made by Jose Federico Gomez. Transforms from hexadecimal to decimal, Both int or string accepted ( Source )
def dec(hex_num):
'''
Use H for help
'''
# Cleaning
hex_num = ''.join(str(hex_num).split()).lower()
if hex_num == 'h':
return """Enter an hexadecimal number:
Only digits str (eg '123abc'),
Integers, (e.g. 123),
or '0x' prefixed str (supports hex() function return value) (eg 0x1af)
"""
if hex_num.startswith('0x'):
hex_num = hex_num[2::]
power = len(hex_num) - 1
dec_ = 0
for char in hex_num:
coefficient = 16 ** power
try:
dec_ += int(char) * coefficient
except ValueError:
correlation = {'a': 10, 'b': 11, 'c': 12, 'd': 13, 'e': 14, 'f': 15,
'A': 10, 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
converted = correlation.get(char, "wrong")
if converted != "wrong":
dec_ += converted * coefficient
else:
raise ValueError("Digit '" + char + "' forbidden. You entered: " + hex_num)
power -= 1
return dec_
print(dec(123))
print(dec('123abc'))
print(dec('0x01af'))
print(dec('0x1af'))
print('In hex it is:', dec(input('Enter an hex number (without quotations): ')))
##################
## Testeo dec() ##
##################
# # NOTE: Selecting several lines and presing Ctrl + / (num keyboard) comments/uncomments the selection
# # ---------------------------------------------------------------------------------------------------
# # Manual Testing:
#
# while True:
# user_input = input("Enter an hexadecimal number (if prefixed, in the form '0x') or Q to Quit: ")
# if user_input.lower() == 'q':
# break
# try:
# print(dec(user_input))
# except ValueError:
# print("Wrong input.")
# continue
# # ---------------------------------------------------------------------------------------------------
# # Autotest 1:
#
# print(dec('h')) # Prints Help
# print(dec('asd')) # Raises error
# # ---------------------------------------------------------------------------------------------------
# # Autotest 2:
# # Won't run until the end in this Playground, with message: Execution Timed Out!
# # Try it in your IDE
#
# # Brute-forced demonstration of successful cancelling for every Unicode Character
# # Bibliography: The Unicode® Standard (v13.0) Core Specification
# # Link: https://www.unicode.org/versions/Unicode13.0.0/
#
# max_code_point = 1_114_112 # 0x10ffff (Section 2.4 Code Points and Characters)
# surrogates_floor = 55296 # 0xd800 (Section 23.6 Surrogates Area)
# surrogates_ceiling = 57343 # 0xdfff (Section 23.6 Surrogates Area)
# available_code_points = max_code_point - (surrogates_ceiling - surrogates_floor + 1) # (Section 23.6 Surrogates Area)
#
# count = 0
# mismatch = list()
# for i in range(0, max_code_point):
# try:
# unicode = chr(dec(hex(i)[2::]))
# if unicode == chr(i):
# print(chr(i), '=', chr(dec(hex(ord(chr(i))))))
# else:
# print('Error at index', count)
# break
# count += 1
# except ValueError:
# print('Error on decimal', i)
# mismatch.append(i)
#
# print('Mismatches =', len(mismatch))
# print(f'\tFrom {mismatch[0]} ({hex(mismatch[0])}) to {mismatch[-1]} ({hex(mismatch[-1])})')
#
# surrogates_match = range(mismatch[0], mismatch[-1]) == range(surrogates_floor, surrogates_ceiling)
# if surrogates_match:
# print(" '-> Surrogates code points match")
# else:
# print(" '-> Surrogates code points don't match")
#
# print('· Total unicode available codepoints =', count)
#
# available_match = count == available_code_points
# if available_match:
# print("'-> Available code points match")
# else:
# print("'-> Available code points Failed")
#
## if surrogates_match and available_match:
# print('\nTest OK')
# else:
# print('\nTest Failed')
# # ---------------------------------------------------------------------------------------------------
4. By Universal Program
Made by Universal Program. ( Source )
hexNum = input("Enter hexadecimal number here: ")
print(int(hexNum, 16))
5. By K D
Made by K D. ( Source )
#Objective: Convert a Hexadecimal number to a Decimal number
def isHexa(num):
flag=True
for i in num:
if not(i in "0123456789ABCDEF."):
flag=False
if num.count(".")>1:
flag=False
return flag
def hexToDec(num):
total=0
if "." in num:
div=num.split(".")
number=div[0]+div[1]
power=len(div[0])-1
else:
power=len(num)-1
number=num
for i in number:
if i in "ABCDEF":
i=(ord(i)-55)
total+=int(i)*(16**power)
power-=1
return total
def main():
num=input("Enter a Hexadecimal number = ")
print("\nHexadecimal Number =",num)
if isHexa(num):
result=hexToDec(num)
print("Decimal Number =",result)
else:
print("Enter a valid Hexadecimal number")
main()
6. By KD
Made by KD. Note: Enter floating point hexadecimal number Ex- Input 19AB2.0 instead of 19AB2. ( Source )
#Checking if input number is Hexadecimal or not
def isHex(num):
flag=True
for i in num:
if not(i in "0123456789ABCDEF."):
flag=False
if num.count(".")>1:
flag=False
return flag
#Converting Hexadecimal number to Decimal Number
def hexToDec(num):
div=num.split(".")
number=(div[0]+div[1])
sum=0
power=(len(div[0])-1)
for i in number:
if i in "ABCDEF":
i=(ord(i)-55)
sum+=int(i)*(16**power)
power-=1
return sum
def main():
num=input("Enter a number = ")
if isHex(num):
result=hexToDec(num)
print(num,"in Decimal =",result)
else:
print("Enter a valid Hexadecimal number")
main()
7. By Thirunalankumar
Made by Thirunalankumar. ( Source )
conversion_table = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'A': 10 , 'B': 11, 'C': 12, 'D': 13, 'E': 14, 'F': 15}
hexadecimal = input("Enter the hexadecimal number: ").strip().upper()
decimal = 0
#computing max power value
power = len(hexadecimal) -1
for digit in hexadecimal:
decimal += conversion_table[digit]*16**power
power -= 1
print(decimal)
8. By Kaushik Nandan
Made by Kaushik Nandan. ( Source )
hex = input()[::-1].upper()
key = {'A':10,'B':11,'C':12,'D':13,'E':14,'F':15, '1':1, '2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8}
dec = 0
for i in range(len(hex)):
dec += int(key[hex[i]])*(16**i)
print(dec)
9. By NS236
Made by NS236. ( Source )
places='0123456789ABCDEF'
def convert(string = str(input())[::-1], output = 0, iterate = 0):
if len(string) == 0:
print(output)
else:
convert(string[1:], output + places.index(string[0]) * 16**iterate, iterate + 1)
convert()
10. By Malek Alsset
Made by Malek Alsset. ( Source )
def hexadecimalToDecimal(hexval):
# Finding length
length = len(hexval)
# Initialize base value to 1,
# i.e. 16*0
base = 1
dec_val = 0
# Extracting characters as digits
# from last character
for i in range(length - 1, -1, -1):
# If character lies in '0'-'9',
# converting it to integral 0-9
# by subtracting 48 from ASCII value
if hexval[i] >= '0' and hexval[i] <= '9':
dec_val += (ord(hexval[i]) - 48) * base
# Incrementing base by power
base = base * 16
# If character lies in 'A'-'F',converting
# it to integral 10-15 by subtracting 55
# from ASCII value
elif hexval[i] >= 'A' and hexval[i] <= 'F':
dec_val += (ord(hexval[i]) - 55) * base
# Incrementing base by power
base = base * 16
return dec_val
if __name__ == '__main__':
hexnum = '1A'
print(hexadecimalToDecimal(hexnum))
11. By Yashvant Kumar
Made by Yashvant Kumar. Python program that converts hexadecimal to decimal. ( Source )
hexadecimal=int(input())
p=n=power=0
hexa=hexadecimal
while hexadecimal!=0:
p=hexadecimal%10
n+=(16**power)*p
hexadecimal//=10
power+=1
print("The decimal no. of",hexa,"is",n)
12. By Wan-develop
Made by Wan-develop. ( Source )
#convert Hexadecimal to Decimal
def hex_to_dec(code):
alphas = {
'a':10,
'b':11,
'c':12,
'd':13,
'e':14,
'f':15
}
hexa = []
for c in code:
for k,v in alphas.items():
if c == k:
c = v
hexa.append(c)
#covert all to int
hexa = map(lambda x: int(x),hexa)
#calculating the the values
hexas = [n*16**i for i,n in enumerate(hexa)]
#returning the sum of all values
return sum(hexas)
if __name__ == "__main__":
hexadecimal = input("hexadecimal: ")
decimal = hex_to_dec(hexadecimal)
print(decimal)
13. By luanyibo
Made by luanyibo. Gets the hexadecimal from input file and outputs decimal. ( Source )
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' Parser txt file tobe excel file.'
__author__ = 'Luan Yi Bo'
import xlwt
import argparse
PATH_TXT_FILE = "example.txt"
class HexToDec(object):
un_valid_num = 208 # Invalid number of bytes in hex document
ex_max_col_num = 16 # excel number of columns
# Is it even
def is_even(self, num):
if num % 2 != 0:
return False
return True
# 2 hexadecimal combined decimal data
def synthesizer(self, num, data):
return data[num] * 256 + data[num + 1]
# Read the data to be processed
def read_data(self, path=None):
if path==None:
return
with open(path, "rb") as f:
un_valid_buf = f.read(self.un_valid_num) # read-ahead processing
need_parse_buf = f.read() # needs to be processed
return need_parse_buf
# Data processing
def processing_data(self, need_parse_buf):
decimal_num = []
for num in range(len(need_parse_buf)):
if not self.is_even(num):
continue
decimal_num.append(self.synthesizer(num, need_parse_buf))
return decimal_num
def parse(self, read_path=None, write_path=None):
# Analytical data
need_parse_buf = self.read_data(read_path)
decimal_num = self.processing_data(need_parse_buf)
# written as excel
self.write_xls_file(write_path, decimal_num)
return
def write_xls_file(self, path, data):
# Create workbook
f = xlwt.Workbook()
# createsheet
sheet1 = f.add_sheet(u'sheet1', cell_overwrite_ok=True)
# write the text
for row in range(int(len(data)/self.ex_max_col_num)+1):
for col in range(self.ex_max_col_num):
if row*16+col > len(data)-1:
break
sheet1.write(row, col, data[row*16+col])
# save document
if path == None:
path = '16to10.xls'
f.save(path)
return
def main(args):
read_path = args.read_file_txt
write_path= args.write_excel
ret = HexToDec()
ret.parse(read_path, write_path)
return
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser(description="Parse hexadecimal data into decimal。。。")
arg_parser.add_argument("-read", "--read_file_txt", help="data source")
arg_parser.add_argument("-write" , "--write_excel", help="filename to write")
args = arg_parser.parse_args()
main(args)
14. By ZrefiXiord
Made by ZrefiXiord. A converter from hexadecimal to decimal using python 3.9. ( Source )
values = {"0":0, "1":1, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8": 8, "9": 9, "A": 10, "B": 11, "C":12, "D":13, "E": 14, "F":15}
def hexadecimal_to_decimal(number):
list=[]
number = number.upper()
sum=0
power=0
for i in number:
list.append(i)
list.reverse()
for i in list:
t=values.get(i)
sum=sum+t*16**power
power=power+1
return sum
print(hexadecimal_to_decimal(input("Please put a hexadecimal number : ")))
15. By Knowledgeless
Made by Knowledgeless. ( Source )
###############################################
# #
# Convert From Hexadecimal To Decimal #
# #
###############################################
print('''
--------------------------
Hexadecimal to Decimal
--------------------------
''')
def con(n,b):
x = n.upper() # If user input small char it will convert into upper char
d = len(n)-1
l = 0
for i in x:
if(i > "F"): # User may input more than 'f/F' which is incorrect.
print("Invalid Input According To base ")
exit()
else:
h = int(i, 16)
l += h*(b**d) # Formula to convert the base
d = d-1
print(l) # Printing the result
n = input("Enter The Hexadecimal Value: ")
b = 16
print("Your Decimal Value Is: ")
con(n,b)
16. By LukaJanela
Made by LukaJanela. A simple script which convert hexadecimal to decimal. ( Source )
#start_over variable controls outer loop and terminates whole program if it's false
start_over = True
while start_over:
print ('\n-------This program converts hexadecimal to decimal-------\n')
#takes hex input as string and reverses it
#reversal is needed so I can start from the back of the number
# therefore going up in powers(0, 1, 2...)
hex_input = input('Input your hexadecimal number: ')[::-1]
#decimal output adds up every number in for loop
#power is used in for loop to raise 16 to the appropriate power
decimal_output = 0
power = 0
#dictionary of hexadecimal characters to convert A-F, a-f to decimal numbers
hex_dict = {'A':10, 'B':11, 'C':12, 'D':13, 'E':14, 'F':15, 'a':10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15}
#iterates over inputted string
for char in hex_input:
#if a char is in above dictionary, find it's value, raise 16 to the power variable and multiply by this value
if char in hex_dict:
decimal_output += hex_dict[char] * (16**power)
power += 1
#if char is not in dictionary, then it's just a decimal as string
else:
#convert it to integer and do the same operations on it as above
decimal_output += int(char) * (16**power)
power += 1
print ('Your decimal number is: ' + str(decimal_output) + '\n')
#yes_no variable controls inner loop, when user has to input y/n to start over or terminate program
yes_no = True
while yes_no:
#ask user for input
terminator = input ('Would you like to continue? (y/n): ')
#if answer's y, get out of this loop and start the program from again (outer loop is still true)
if terminator == 'y':
yes_no = False
#if answer's n, get out of both loops, therefore, terminating program altogether
elif terminator == 'n':
yes_no = False
start_over = False
#if user inputs anything else than y/n, it's incorrect input, therefore we ask him again for input
else:
continue
17. By pythonman1
Made by pythonman1. ( Source )
#!/usr/bin/python3
######################### BISMI ALLAH ##################################### Coding like a PRO! ###############################
import sys, subprocess
hex_vals = '0123456789ABCDEF'
def part_1(hex_val, power):
dec_val = 0
try:
for i in range(0,len(hex_val)):
power -= 1
for j in range(0,len(hex_vals)):
if hex_val[i] == hex_vals[j]:
dec_val += j * 16**(power)
except IndexError:pass
return dec_val
def part_2(hex_val, power):
dec_val = 0
try:
for i in range(0,len(hex_val)):
power -= 1
for j in range(0,len(hex_vals)):
if hex_val[i] == hex_vals[j]:
dec_val += j * 16**(power)
except IndexError:pass
return dec_val
while True:
try:
hex_val, clear, fractional_part, = "", False,''
hex_val = input("[*] HEX: ")
if not hex_val:continue
f_part = False
for i in range(len(hex_val)):
if hex_val[i:i + 5] == 'clear':
clear = subprocess.Popen("clear", shell = True, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
clear = clear.stdout.read()
clear = str(clear, 'utf-8')
print("{}".format(clear))
clear = True
break
if hex_val[i:i + 4] in ("Exit",'exit','quit','Quit','q','Q'):
sys.exit(0)
if hex_val[i] == '.' and not f_part:
fractional_part = hex_val[i + 1:].upper()
f_part = True
if clear: continue
hex_val = hex_val.upper()
problem = False
for k in range(len(hex_val)):
if hex_val[k] == '.':continue
problem_ = True
for h in range(len(hex_vals)):
if hex_val[k] == hex_vals[h]:
problem_ = False
break
if problem_:
print("[!] Invalide Hexadecimal value.")
problem = True
break
if problem: continue
if fractional_part:
for i in range(len(fractional_part)):
if fractional_part[i] == '.':
print("[!] Invalide Hexadecimal value.")
problem = True
break
if problem:continue
intiger_part = ''
for i in range(len(hex_val)):
if hex_val[i] == '.':
break
intiger_part += hex_val[i]
intiger_part = part_1(intiger_part, len(intiger_part))
fractional_part = part_2(fractional_part, 0)
print("[+] Dec: %f" % (intiger_part + fractional_part))
except KeyboardInterrupt:sys.stdout.write("\n")
################################################### Al hamdu liLAH ########################################################
18. By lewis-conroy
Made by lewis-conroy. Functions for converting values from hexadecimal to decimal and back. ( Source )
def hex_to_decimal(hex_in):
global hex_dict
decimal_out = 0
list_hex_in = list(hex_in)
list_hex_in.reverse()
base = 1
for i in list_hex_in:
for k, v in hex_dict.items():
if v is i:
decimal_out += k * base
break
elif k == 15:
decimal_out += int(i) * base
base *= 16
return decimal_out
19. By r0gu3cic
Made by r0gu3cic. ( Source )
def hex_to_dec(hex):
dec=int(hex, base=16)
return dec
def bin_to_dec(bin):
dec=int(bin,base=2)
return dec
def hex_to_bin(hex):
binary=bin(int(hex, base=16))[2:]
return binary
def dec_to_bin(dec):
binary=bin(int(dec))[2:]
return binary
def dec_to_hex(dec):
hexa=hex(int(dec))[2:]
return hexa
def bin_to_hex(bin):
dec=bin_to_dec(bin)
hexa=dec_to_hex(dec)
return hexa
###MAIN###
print('''This is simple numerical system converter used to convert hexadecimal,
decimal or binary number to hexadecimal, decimal or binary number''')
while True:
choice=input('''What number type you need to convert?
1-Binary
2-Decimal
3-Hexadecimal
Choice: ''')
if choice not in ['1','2','3']:
continue
elif choice=='1':
num=input('Input your binary number: ')
dec=bin_to_dec(num)
print('Your number converted to decimal: '+str(dec))
hex=bin_to_hex(num)
print('Your number converted to hexadecimal: '+str(hex))
break
elif choice=='2':
num=input('Input your decimal number: ')
binary=dec_to_bin(num)
print('Your number converted to binary: '+str(binary))
hex=dec_to_hex(num)
print('Your number converted to hexadecimal: '+str(hex))
break
elif choice=='3':
num=input('Input your hexadecimal number: ')
binary=hex_to_bin(num)
print('Your number converted to binary: '+str(binary))
dec=hex_to_dec(num)
print('Your number converted to decimal: '+str(dec))
break
20. By jmunro4
Made by jmunro4. ( Source )
# convert.py
# Jonathan Munro
# 1/25/2017
''' This program prints the Binary, Decimal, and Hexadecimal notations for a given number.
The user must provide the number and select the starting notation from console prompts. '''
import sys
def bin2dec(string):
decNum = 0
count = 0
for i in range(len(string)-1, -1, -1):
decNum += (2**count) * int(string[i])
count += 1
return str(decNum)
def bin2hex(string):
#return dec2hex(bin2dec(string))
hexNum = ""
if(len(string)%4 !=0):
string = ("0"*(4-(len(string)%4))) + string
while(len(string) != 0):
hexStr = string[-4:]
string = string[:-4]
decNum = 0
count = 0
for i in range(3, -1, -1):
decNum += (2**count) * int(hexStr[i])
count += 1
if(decNum > 9):
alist = ['A', 'B', 'C', 'D', 'E', 'F']
hexNum = alist[decNum - 10] + hexNum
else:
hexNum = str(decNum) + hexNum
return hexNum
def dec2bin(string):
binNum = ""
intStr = int(string)
while(intStr != 0):
binNum = str(intStr%2) + binNum
intStr = intStr//2
if(len(binNum)%4 != 0):
binNum = ("0"*(4-(len(binNum)%4))) + binNum
return binNum
def dec2hex(string):
hexNum = ""
intStr = int(string)
alphList = ['A', 'B', 'C', 'D', 'E', 'F']
while(intStr != 0):
if (intStr%16) <= 9:
hexNum = str(intStr%16) + hexNum
else:
hexNum = alphList[intStr%16 - 10] + hexNum
intStr = intStr//16
return hexNum
def hex2bin(string):
#return dec2bin(hex2dec(string))
binNum = ""
count = 0
for i in range(len(string)-1, -1, -1):
if string[i] in ['A','B','C','D','E','F']:
decNum = ord(string[i])-55
else:
decNum = int(string[i])
for i in range(4):
binNum = str(decNum%2) + binNum
decNum = decNum//2
return binNum
def hex2dec(string):
decNum = 0
count = 0
for i in range(len(string)-1, -1, -1):
if string[i] in ['A','B','C','D','E','F']:
decNum += (16**count) * (ord(string[i])-55)
else:
decNum += (16**count) * int(string[i])
count += 1
return str(decNum)
def main():
cont = 'y'
while cont == 'y':
num = input("\nnumber (exclude any spaces or '0x'): ")
data0 = input("number notation (bin/dec/hex): ")
if data0 == "bin":
print("bin =", num)
print("dec =", bin2dec(num))
print("hex =", bin2hex(num))
elif data0 == "dec":
print("bin =", dec2bin(num))
print("dec =", num)
print("hex =", dec2hex(num))
elif data0 == "hex":
print("bin =", hex2bin(num.upper()))
print("dec =", hex2dec(num.upper()))
print("hex =", num.upper())
else:
print("number type not recognized")
cont = input("again? (y/n) :")
main()
21. By vKorantin
Made by vKorantin. ( Source )
# General.
forme_depart_valide = False
forme_arrivee_valide = False
# Functions.
def convertir_forme(forme):
while forme != "1" or forme != "2" or forme != "3":
if forme == "1":
new_forme = "binary"
return new_forme
elif forme == "2":
new_forme = "decimal"
return new_forme
elif forme == "3":
new_forme = "hexadecimal"
return new_forme
else:
forme = input("Enter the corresponding number : ")
# From binary.
def con_bin_dec(mot):
print()
mot_final = 0
mot_depart = mot
mot_a_traduire = []
for i in range(0, len(mot_depart), 1):
mot_a_traduire.append(int(mot_depart[i]))
mot_a_traduire.reverse()
for i in range(0, len(mot_a_traduire), 1):
mot_final += mot_a_traduire[i]*2**i
return mot_final
def con_bin_hex(mot):
print()
mot_depart = mot
decimal = con_bin_dec(mot_depart)
mot_final = con_dec_hex(decimal)
return mot_final
# Starting from decimal.
def con_dec_bin(mot):
print()
mot_final = []
mot_final_conv = ""
mot_depart = int(mot)
while mot_depart > 0:
mot_final.append(mot_depart % 2)
mot_depart = int(mot_depart / 2)
mot_final.reverse()
for elt in mot_final:
mot_final_conv += str(elt)
return mot_final_conv
def con_dec_hex(mot):
print()
mot_final = []
mot_final_conv = ""
mot_depart = int(mot)
while mot_depart > 0:
mot_final.append(mot_depart % 16)
mot_depart = int(mot_depart / 16)
mot_final.reverse()
for elt in mot_final:
if elt == 10:
mot_final_conv += "A"
elif elt == 11:
mot_final_conv += "B"
elif elt == 12:
mot_final_conv += "C"
elif elt == 13:
mot_final_conv += "D"
elif elt == 14:
mot_final_conv += "E"
elif elt == 15:
mot_final_conv += "F"
else:
mot_final_conv += str(elt)
return mot_final_conv
#From the hexadecimal.
def con_hex_bin(mot):
print()
mot_final = []
mot_final_conv = ""
mot_depart = mot
mot_a_traduire = []
for i in range(0, len(mot_depart), 1):
mot_a_traduire.append(mot_depart[i].upper())
for elt in mot_a_traduire:
if elt == "A":
mot_final.append(10)
elif elt == "B":
mot_final.append(11)
elif elt == "C":
mot_final.append(12)
elif elt == "D":
mot_final.append(13)
elif elt == "E":
mot_final.append(14)
elif elt == "F":
mot_final.append(15)
else:
mot_final.append(int(elt))
for elt in mot_final:
mot_final_conv += str(con_dec_bin(elt))
return mot_final_conv
def con_hex_dec(mot):
print()
mot_depart = mot
binaire = con_hex_bin(mot_depart)
mot_final = con_bin_dec(binaire)
return mot_final
###################################################################################################################
# Conversion choice.
print("What form is the word to be translated?")
print()
print("1. Binary")
print("2. Decimal")
print("3. Hexadecimal")
print()
forme_depart = input("Enter the corresponding number : ")
while forme_depart_valide == False:
try:
int(forme_depart)
except ValueError:
forme_depart = input("Enter the corresponding number : ")
else:
forme_depart = convertir_forme(forme_depart)
forme_depart_valide = True
print("In what form do you want to translate it?")
print()
print("1. Binary")
print("2. Decimal")
print("3. Hexadecimal")
print()
forme_arrivee = input("Enter the corresponding number: ")
while forme_arrivee_valide == False:
try:
int(forme_arrivee)
except ValueError:
forme_arrivee = input("Enter the corresponding number : ")
else:
forme_arrivee = convertir_forme(forme_arrivee)
forme_arrivee_valide = True
# If the two forms are identical.
if forme_depart == forme_arrivee:
print("They are the same forms, the word is already translated.")
print()
choix_mot = input("Enter the word to translate: ")
print()
# Choix de la fonction.
if forme_depart == "binary":
if forme_arrivee == "decimal":
input("The decimal number of {} is {}.".format(choix_mot, con_bin_dec(choix_mot)))
elif forme_arrivee == "hexadecimal":
input("The hexadecimal number of {} is {}.".format(choix_mot, con_bin_hex(choix_mot)))
elif forme_depart == "decimal":
if forme_arrivee == "binary":
input("The binary number of {} is {}.".format(choix_mot, con_dec_bin(choix_mot)))
elif forme_arrivee == "hexadecimal":
input("The hexadecimal number of {} is {}.".format(choix_mot, con_dec_hex(choix_mot)))
elif forme_depart == "hexadecimal":
if forme_arrivee == "binary":
input("The binary number of {} is {}.".format(choix_mot.upper(), con_hex_bin(choix_mot)))
elif forme_arrivee == "decimal":
input("The hexadecimal number of {} is {}.".format(choix_mot.upper(), con_hex_dec(choix_mot)))