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()
Answer
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()
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module