Reputation: 13
I have another problem with a program that converts binary digits to hexadecimal. I have the program that runs well but displays the hexadecimal digit in small caps though the answer is required to be in caps as shown in the question and sample run
This is my code
def binaryToHex(binaryValue):
#convert binaryValue to decimal
decvalue = 0
for i in range(len(binaryValue)):
digit = binaryValue.pop()
if digit == '1':
decvalue = decvalue + pow(2, i)
#convert decimal to hexadecimal
hexadecimal=hex(decvalue)
return hexadecimal
def main():
binaryValue = list(input("Input a binary number: "))
hexval=binaryToHex(binaryValue)
hexa=h1.capitalize() #Tried to use capitalize() function but didn't worl
print("The hex value is",hexa[ 2:4]) #strips off the first 2 digits
main()
This is what is displayed when I run
Upvotes: 1
Views: 1120
Reputation: 142216
Since this comes up a fair bit - here's an answer that's fairly Pythonic and hopefully serves as a canonical reference for future questions.
First off, just keep the input as a string:
binary_value = input('Enter a binary number: ')
Then use the builtin int
with a base
argument of 2 (which indicates to interpret the string as binary digits) to get an integer from your string:
number = int(binary_value, 2)
# 10001111 -> 143
Then you can use an f-string
to print your number with a format specifier X
which means in "hex with upper case letters and no prefix":
print(f'The hex value is {number:X}')
Your entire code base would then be something like (sticking with two-functions and your naming conventions):
def binaryToHex(binaryValue):
number = int(binaryValue, 2)
return format(number, 'X')
def main():
binaryValue = input('Enter a binary number: ')
print('The hex value is', binaryToHex(binaryValue))
main()
Upvotes: 1
Reputation: 416
just make one function...
def binaryToHex():
binval = input('Input a binary number : ')
num = int(binval, base=2)
hexa = hex(num).upper().lstrip('0X')
print(f'The hex value is {hexa}')
Upvotes: 0
Reputation: 390
One mistake you've made is h1 does not exist in the code and yet it's present.
.upper() on a string changes it to uppercase
def main():
binaryValue = list(input("Input a binary number: "))
hexval=binaryToHex(binaryValue)
hexa=hexval.upper()
print("The hex value is",hexa[ 2:4]) #strips off the first 2 digits
output:
Input a binary number: 10001111
The hex value is 8F
Upvotes: 0