'Trying to convert Binary to Decimal to Hexadecimal in Python without inbuilt Functions
So I'm trying to use Python to convert a Binary number to a Decimal number to a Hexadecimal number.
I need to use functions for this, but not the inbuilt ones. Specifically, I want to use a binToDec (binary to decimal) function, a decToHex (decimal to hexadecimal function), and lastly the main function where all the code will run. Below is what I have done thus far, and it has several errors, but my brain is spent on this and I was hoping to get some collaborative help. Thanks!
Edit: The errors are with returning hex_value and calling hex_num
def binToDec (binary):
count = 1
dnum=0
while(binary != 0):
rem = binary % 10
dnum = dnum + (rem * count)
count = count * 2
binary = int(binary / 10)
return binary
def decToHex (dnum):
while (dnum > 0):
hex_value = dnum % 16
dnum = dnum // 16
if (dnum < 10):
return str(hex_value)
elif (dnum == 10):
return "A"
elif (dnum == 11):
return "B"
elif (dnum == 12):
return "C"
elif (dnum == 13):
return "D"
elif (dnum == 14):
return "E"
elif (dnum == 15):
return "F"
return hex_value
def main():
binary = int(input("Please enter a binary number: "))
dec_num = binToDec(binary)
hex_num = decToHex(dec_num)
print("You entered the hexadecimal number: " + str(hex_num))
main()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
