Python Function To Convert Binary Digit To Hexadecimal

- 1 answer

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
return hexadecimal
def main():
  binaryValue = list(input("Input a binary number: "))

  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

This is what is displayed when I run



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