简体   繁体   中英

Python function to convert Binary digit to Hexadecimal

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM