This post contains a total of 32+ Hand-Picked Python Decimal to Hexadecimal Converter Examples. All the Decimal to Hexadecimal converters are made using Python Programming language.
You can use the source codes 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 Ashton Rowe
Made by Ashton Rowe. A simple Python program to convert decimal number to hexadecimal. ( Source )
print('Decimal to Hexadecimal Converter\nBy Ashton Rowe\n')
while True:
dec_value = int(input('Enter decimal number: '))
hexcode = '0123456789ABCDEF'
answer = ''
negative = False
if dec_value < 0:
negative = True
dec_value = -dec_value
while dec_value != 0:
quotient = dec_value / 16
remainder = dec_value % 16
dec_value = int(quotient)
hex_value = hexcode[remainder]
answer = hex_value + answer
if negative == True:
answer = '-' + answer
print('\nHex equivalent is:',answer)
break
2. By Manish Kumar Pandit
Made by Manish Kumar Pandit. ( Source )
n=int(input())
z=[]
for e in range(n):
z.append(str(n%16))
n = n//16
if n==0:
break
k=z[::-1]
#print(k)
k = ["A" if x=="10" else x for x in k]
k = ["B" if x=="11" else x for x in k]
k = ["C" if x=="12" else x for x in k]
k = ["D" if x=="13" else x for x in k]
k = ["E" if x=="14" else x for x in k]
k = ["F" if x=="15" else x for x in k]
#print(k)
print("".join(k))
3. By Universal Program
Made by Universal Program. A small two line program to convert decimal into hexadecimal. ( Source )
decimalNum = input("Enter decimal number here: ")
print(hex(int(decimalNum)))
4. By Priyanshu Sharma
Made by Priyanshu Sharma. ( Source )
dec = int(input())
oct = oct(dec)
print("A number with the prefix '0b' is considered binary, '0o' is considered octal and '0x' as hexadecimal.\n\n")
print("the octal equivalent is ", oct)
bin = bin(dec)
print("\nthe binary equivalent is ", bin)
hexa = hex(dec)
print("\nthe hexadecimal equivalent is ", hexa)
5. By Yashvant Kumar
Made by Yashvant Kumar. ( Source )
n=int(input())
n1=n
hexa=h=''
hexadecimal=0
i=p=0
while n>0:
p=n%16
hexa+=str(p)
n//=16
hexadecimal=hexa
i=len(hexadecimal)
while i!=0:
h+=hexadecimal[i-1]
i-=1
print("The hexadecimal of",n1,"is:",h)
6. By Hareesh Yadla
Made by Hareesh Yadla. The program will print the hexadecimal value of all the previous numbers of the decimal number entered. ( Source )
n = int(input())
w = len(bin(n)[2:])
f = "{0:" + str(w) + "d} " +"{0:" + str(w) + "o} " +"{0:" + str(w) + "X} " +"{0:" + str(w) + "b} "
print("Dec-> Oct-> Hex-> Bin\n")
for i in range(1,n+1):
print(f.format(i))
7. By Mihai Apostol
Made by Mihai Apostol. ( Source )
#code returning hexadecimal number from #decimal number
def dec2hex(number):
rev_hex = "" #define empty string
result = -1 #to start the loop
while result != 0:
result = number // 16 #floor division
reminder = number % 16 #keep reminder
if reminder <= 9:
rev_hex += str(reminder)
elif reminder == 10:
rev_hex += "a"
elif reminder == 11:
rev_hex += "b"
elif reminder == 12:
rev_hex += "c"
elif reminder == 13:
rev_hex += "d"
elif reminder == 14:
rev_hex += "e"
elif reminder == 15:
rev_hex += "f"
number = result #next iteration
return rev_hex[::-1] #reverse string
print(dec2hex(int(input()))) #call function
'''
#v2.0 (with dictionary)
def dec2hex(number):
rev_hex = "" #define empty string
result = -1 #to start the loop
reminders={0: 0, 1: 1, 2: 2, 3: 3, 4: 4,
5: 5, 6: 6, 7: 7, 8: 8, 9: 9,
10: "a", 11: "b", 12: "c",
13: "d", 14: "e", 15: "f"}
while result != 0:
result = number // 16 #floor division
reminder = number % 16 #keep reminder
rev_hex += str(reminders[reminder])
number = result #next iteration
return rev_hex[::-1] #reverse string
print(dec2hex(int(input() or 11259375))) #call function
'''
'''
#v3.0 (with string)
def dec2hex(n):
rev_hex = ""
hex = "0123456789abcdef"
while n != 0:
rev_hex+=hex[n%16]
n//=16
return rev_hex[::-1]
print(dec2hex(int(input() or 11259375)))
'''
8. By Vismay Katharani
Made by Vismay Katharani. Basic Python decimal to hexadecimal converter program. ( Source )
dec = int(input("Enter a Decimal Number:\n"))
print(hex(dec), "in hexadecimal.")
9. By KD
Made by KD. ( Source )
#Objective: To Convert a Decimal number to Hexadecimal number
def decIntToHex(num):
result1=""
while(num>0):
rem=num%16
if rem<10:
result1=str(rem)+result1
else:
result1=chr(rem+55)+result1
num//=16
return result1
def decFracToHex(fraction):
i=0
result2=""
while(i<5):
mult=fraction*16
y=int(mult)
if y<10:
result2=str(result2)+str(y)
else:
result2=str(result2)+chr(y+55)
fraction=mult-y
i+=1
return result2
def main():
num=float(input("Enter a Decimal number = "))
integer=int(num)
fraction=num-integer
result1=decIntToHex(integer)
result2=decFracToHex(fraction)
result=str(result1)+"."+str(result2)
print(num,"in Hexadecimal =",result)
main()
10. By Issa
Made by Issa. ( Source )
#integer assertion
try :
n=int(input())
except ValueError :
print("Positive integers only.")
#positive integer assertion
assert n>=0, "Positive integers only."
hex={0:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"A",11:"B",12:"C",13:"D",14:"E",15:"F",16:"10"}
q=n//16
r=n%16
f=[r]
while q!=0 :
r=q%16
q=q//16
f.append(r)
f.reverse()
if 16>=n>=0 :
print(hex[n])
else :
for t in f :
print(hex[t], end="")
11. By Gaming Innovations
Made by Gaming Innovations. ( Source )
def dectohexreverse(x):
a = ""
x = int(x)
c = x
while x > 0:
y = x % 16
b = dectohexreverse(x // 16)
x = 0
if y == 15:
a = a + "F"
if y == 14:
a = a + "E"
if y == 13:
a = a + "D"
if y == 12:
a = a + "C"
if y == 11:
a = a + "B"
if y == 10:
a = a + "A"
elif y < 10:
a = a + str(y)
if c > 0:
return a + b
else:
return a
def dectohex(x):
a = dectohexreverse(x)
d = ""
for i in range(len(a)):
d = d + a[len(a)-i-1]
return d
inp = input()
print("The hexadecimal number will be ",dectohex(inp),".\nFrom the input of ", inp)
12. By Akash
Made by Akash. The program will print the hexadecimal value of a decimal number along with octal and binary. ( Source )
def dec_convert(s_sys,system,num):
bin = []
while num>=system:
temp = num%system
if temp>9:
temp = chr(65+(temp-10))
num //= system
bin.append(temp)
if num>9:
num = chr(65+(num-10))
bin.append(num)
print('In '+s_sys,end='')
res = ''
for x in list(reversed(bin)):
res += str(x)
print(res)
num = int(input("Enter any number of base 10 : \n"))
print("In Decimal : "+str(num))
dec_convert("Binary : ",2,num)
dec_convert("Octal : ",8,num)
dec_convert ("Hexadecimal : ",16,num)
13. By B2 Abhishek Gupta
Made by B2 Abhishek Gupta. ( Source )
# built-in function hex()
n=int(input("Enter the decimal number :"))
result=0
lis=[]
print(n)
while(n>0):
a=n%16 #remainder
if(a==10):a="A"
elif (a==11):a="B"
elif (a==12):a="C"
elif (a==13):a="D"
elif (a==14):a="E"
elif (a==15):a="F"
lis.insert(0,str(a))
n//=16 #qutioent
if(len(lis)>1):
result ="".join(list(lis))
else :
result =a
print("Hexadecimal of entered value :",result)
14. By Erik Johanson
Made by Erik Johanson. ( Source )
decToHex = {0: '0', 1:'1', 2:'2', 3:'3', 4:'4', 5:'5', 6:'6', 7:'7', 8:'8', 9:'9', 10:'A', 11:'B', 12:'C', 13:'D', 14:'E', 15:'F'}
dec = int(input())
hex = ''
while dec > 0:
hex = decToHex[dec % 16] + hex
dec //= 16
print(hex)
15. By Mohamad Hashemi
Made by Mohamad Hashemi. ( Source )
a=int(input())
number=a
hex={10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}
hex_list=[]
while(a>0):
a=a/16
f=a-int(a)
f=f*16
hex_list.append(f)
a=int(a)
hexadecimal=''
for i in hex_list:
for j in list(hex.keys()):
if(i==j):
hexadecimal+=hex[j]
break
elif(i>10):
hexadecimal+=hex[i]
break
else:
hexadecimal+=str(int(i))
break
print("Hexadecimal",number,"=",hexadecimal[::-1])
16. By Tenor
Made by Tenor. You have to put in a decimal number (base 10)inside the input box. ( Source )
import math
opo = int(input("put in your number. "))
num = hex(opo)
print("your number was " + str(opo) + ", and converted to hex it is " + num)
17. By Dushan Rachintha
Made by Dushan Rachintha. ( Source )
b = " "
d = int(input(" Your hexadecimal = "))
while d>0 :
r = d % 16
if r == 10 :
r = "A"
elif r == 11 :
r = "B"
elif r == 12 :
r = "C"
elif r == 13 :
r = "D"
elif r == 14 :
r = "E"
elif r == 15 :
r = "F"
else :
r = str (r)
b = r+b
d = d // 16
print (b)
18. By MasterBurnt
Made by MasterBurnt. ( Source )
#Convert decimal number in hexadecimal
#MrBurnt
dec = int(input("Enter a number ~> "))
dec += 1
for i in range(1,dec):
print("\ndecimal~>", i, "hexadecimal~>",hex(i))
19. By Baran
Made by Baran. Python program to convert decimal to hexadecimal. ( Source )
def Hex(x):
list = []
while x >= 16:
r = x % 16
x = x // 16
if r == 10:
list.append("A")
elif r == 11:
list.append("B")
elif r == 12:
list.append("C")
elif r == 13:
list.append("D")
elif r == 14:
list.append("E")
elif r == 15:
list.append("F")
else:
list.append(r)
if x < 16:
if x == 10:
list.append("A")
elif x == 11:
list.append("B")
elif x == 12:
list.append("C")
elif x == 13:
list.append("D")
elif x == 14:
list.append("E")
elif x == 15:
list.append("F")
else:
list.append(x)
alist = list[::-1]
for i in alist:
print (i,end="")
print("Enter a number")
inp = input("")
inpu = int(inp)
Hex(inpu)
20. By Carlos Eduardo de Jesus Barreto
Made by Carlos Eduardo de Jesus Barreto. ( Source )
# Enter number you want to convert;
decimal = int(input ("Please insert the number you want to convert:"))
# Definition of variables
resto = ""
hexa = []
# The convertion account
while decimal >= 16:
resto = decimal % 16
# Here i created a list to get all numbers from de division
hexa.append (resto)
decimal = decimal // 16
# This last append is to append the last number, that is under 16;
hexa.append (decimal)
# Reverse the list to get the approprieted sequence;
hexa.reverse()
# Here is the conversion of the numbers between 10 and 16 to the matching letters
for n, i in enumerate (hexa):
if i == 10:
hexa [n] = "A"
if i == 11:
hexa [n] = "B"
if i == 12:
hexa [n] = "C"
if i == 13:
hexa [n] = "D"
if i == 14:
hexa [n] = "E"
if i == 15:
hexa [n] = "F"
# And this last code is to print de list as one string;
for i in hexa:
print (i, end="")
21. By m8riix
Made by m8riix. #input – Enter Any Decimal Number #output – Hexadecimal Of That Number. ( Source )
inp=int(input())
print("HexaDecimal Of " + str(inp) + " is " + str(hex(inp)).lstrip("0x").upper())
22. By Uros Tanasic
Made by Uros Tanasic. ( Source )
dec = int(input("Enter any Number: "))
print (" The decimal value of" ,dec, "is:")
print (bin(dec)," In binary.")
print (oct(dec),"In octal.")
print (hex(dec),"In hexadecimal.")
23. By Gonzalo Gonzalez
Made by Gonzalo Gonzalez. Change ‘n=65029’ to the decimal number you want to use. ( Source )
dig=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"]
def conversor(n):
a=n%16
res=n//16
if res==0:
return dig[a]
else:
return conversor(res)+dig[a]
n=65029
print (conversor(n))
24. By Sylas Varga
Made by Sylas Varga. ( Source )
def hnum(i1):
if i1 == 10:
return "A"
elif i1 == 11:
return "B"
elif i1 == 12:
return "C"
elif i1 == 13:
return "D"
elif i1 == 14:
return "E"
elif i1 == 15:
return "F"
else:
return i1
def conv(i1,n):
g = []
while True:
g.append(i1%n)
i1 //= n
if i1 == 0:
break
return g
def db(i1):
g,g = [],conv(i1,2)
return ''.join(map(str, g[::-1]))
def do(i1):
g,g = [],conv(i1,8)
return ''.join(map(str, g[::-1]))
def dh(i1):
g = []
while True:
g.append(i1%16)
i1 //= 16
if i1 == 0:
for i in range(len(g)):
g[i] = hnum(g[i])
break
return ''.join(map(str, g[::-1]))
def bd(b):
d,a,b = 0,1,list(str(b))
for i in range(len(b)):
if int(b[::-1][i]) == 1:
d += (int(b[::-1][i])*a)
a *= 2
return d
num = int(input())
print(str(num)+":")
print()
print("In Binary:")
print(db(num))
print()
print("In Octary:")
print(do(num))
print()
print("In Decimal:")
print(num)
print()
print("In Hexadecimal:")
print(dh(num))
25. By Tsatsu Cephas Kwesi
Made by Tsatsu Cephas Kwesi. ( Source )
dec = int(input("Please enter number: "))
bin(dec)
oct(dec)
hex(dec)
print ('The decimal value', dec, ':')
print ('In hexadecimal:', format (dec, 'x'))
26. By NS236
Made by NS236. ( Source )
decimal = int(input())
places = '0123456789ABCDEF'
def convert(num, string):
if num > 0:
convert(num // 16, string + places[int(num % 16)])
else:
print(string[::-1])
convert(decimal, '')
27. By Yash
Made by Yash. ( Source )
x = int(input())
t = []
while x >0:
s = i = 0
i +=x%16
if i == 10:
i = 'A'
s = ""
if i == 11:
i = 'B'
s = ""
if i == 12:
i = 'C'
s = ""
if i == 13:
i = 'D'
s = ""
if i == 14:
i = 'E'
s = ""
if i == 15:
i = 'F'
s = ""
s = s+i
t.append(s)
x = x//16
t.reverse()
print(t)
28. By DEVELOPER
Made by DEVELOPER. Python program to convert decimal into other number systems. Change Dec number to your decimal number. ( Source )
dec = 344
print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")
29. By PotassiumBanana
Made by PotassiumBanana. ( Source )
'''
this is just the hex() function lol
'''
dec = int(input())
print(hex(dec))
30. By Maanyu
Made by Maanyu. ( Source )
#coded by Maanyu
#function to convert decimal to binary
def decimal_into_binary(decimal_1):
decimal = int(decimal_1)
# print the equivalent decimal
print ("The given decimal number", decimal, "in Binary number is: ", bin(decimal))
# function to convert decimal to octal
def decimal_into_octal(decimal_1):
decimal = int(decimal_1)
# print the equivalent decimal
print ("The given decimal number", decimal, "in Octal number is: ", oct(decimal))
# function to convert decimal to hexadecimal
def decimal_into_hexadecimal(decimal_1):
decimal = int(decimal_1)
#print the equivalent decimal
print ("The given decimal number", decimal, " in Hexadecimal number is: ", hex(decimal))
# Driver program
decimal_1 = int (input (" Enter the Decimal Number: "))
decimal_into_binary(decimal_1)
decimal_into_octal(decimal_1)
decimal_into_hexadecimal(decimal_1)
31. By Pooja
Made by Pooja. ( Source )
print("Welcome to the Binary/Hexadecimal Converter App");
# Binary :Base 2 no.system Hexadecimal base:16 decimal base: 10
# Get user input and generate lists:
max_value = int(input("\nCompute binary and hexadecimal values up to the following decimal number:"))
decimal = range(1,max_value+1)
binary = []
hexadecimal = []
for num in decimal:
binary.append(bin(num))
hexadecimal.append(hex(num))
print("Generating lists...complete!")
# print(binary)
# print(hexadecimal)
# print(decimal)
# bin(number)
# number ,Return the binary representation of an integer.
# eg bin(2)
# Get Slicing index from User:
print("Using slices, we will now show a portion of each list.")
lower_range = int(input("What decimal number would you like to start at: "))
upper_range = int(input("What decimal number would you like to stop at: "))
# Slice through each list individually
print("\nDecimal values from " + str(lower_range) + " to " + str(upper_range) + ":")
for num in decimal[lower_range-1:upper_range]:
print(num)
# Since lower_range start from 0 it takes 2 index as 1 therefore lower_range-1
print("\nBinary values from " + str(lower_range) + " to " + str(upper_range) + ":")
for num in binary[lower_range-1:upper_range]:
print(num)
print("\nHexadecimal values from " + str(lower_range) + " to " + str(upper_range) + ":")
for num in hexadecimal[lower_range-1:upper_range]:
print(num)
# Output the whole list to the screen
input("\nPress Enter to see all values from 1 to " + str(max_value) + ".")
print("Decimal----------Binary----------Hexadecimal")
for d, b, h in zip(decimal,binary,hexadecimal):
print(str(d)+ "---------" + str(b) + "---------" + str(h) )
# zip:Here, you use zip(decimal , binary , hexadecimal) to create an iterator
# that produces tuples of the form (x, y ,z).
# In this case, the x values are taken from decimal and the y values are taken from binary.
# z values are taken from hexadecimal.
# Notice how the Python zip() function returns an iterator:
# To retrieve the final list object, you need to use list() to consume the iterator.
32. By Mavic
Made by Mavic. Converts base10 decimal number to base16 hexadecimal. ( Source )
#Using python 3
#base10 to base16 converter
hexNumberArray =[]
base16 = {10:"a",11:"b",12:"c",13:"d",14:"e",15:"f"}
def decimalToHex(decNumber):
remainder = 5
while remainder >= 1:
remainder=int(decNumber % 16)
decNumber /= 16
if remainder > 9:
hexNum=base16[remainder]
hexNumberArray.append(hexNum)
elif remainder == 0:
hexNumberArray.append(int(decNumber))
else:
hexNumberArray.append(remainder)
hexNumberArray.reverse()
result = ''.join(map(str,hexNumberArray))
print("0x"+result)
decNumber = int(input("Enter base10 decimal number:"))
decimalToHex(decNumber)
33. By isaccanedo
Made by isaccanedo. ( Source )
""" Convert Base 10 (Decimal) Values to Hexadecimal Representations """
# set decimal value for each hexadecimal digit
values = {
0: "0",
1: "1",
2: "2",
3: "3",
4: "4",
5: "5",
6: "6",
7: "7",
8: "8",
9: "9",
10: "a",
11: "b",
12: "c",
13: "d",
14: "e",
15: "f",
}
def decimal_to_hexadecimal(decimal: float) -> str:
"""
take integer decimal value, return hexadecimal representation as str beginning
with 0x
>>> decimal_to_hexadecimal(5)
'0x5'
>>> decimal_to_hexadecimal(15)
'0xf'
>>> decimal_to_hexadecimal(37)
'0x25'
>>> decimal_to_hexadecimal(255)
'0xff'
>>> decimal_to_hexadecimal(4096)
'0x1000'
>>> decimal_to_hexadecimal(999098)
'0xf3eba'
>>> # negatives work too
>>> decimal_to_hexadecimal(-256)
'-0x100'
>>> # floats are acceptable if equivalent to an int
>>> decimal_to_hexadecimal(17.0)
'0x11'
>>> # other floats will error
>>> decimal_to_hexadecimal(16.16) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # strings will error as well
>>> decimal_to_hexadecimal('0xfffff') # doctest: +ELLIPSIS
Traceback (most recent call last):
...
AssertionError
>>> # results are the same when compared to Python's default hex function
>>> decimal_to_hexadecimal(-256) == hex(-256)
True
"""
assert type(decimal) in (int, float) and decimal == int(decimal)
decimal = int(decimal)
hexadecimal = ""
negative = False
if decimal < 0:
negative = True
decimal *= -1
while decimal > 0:
decimal, remainder = divmod(decimal, 16)
hexadecimal = values[remainder] + hexadecimal
hexadecimal = "0x" + hexadecimal
if negative:
hexadecimal = "-" + hexadecimal
return hexadecimal
if __name__ == "__main__":
import doctest
doctest.testmod()