Write a program that reads a binary string (string of 0’s and 1’s) converting the binary value into decimal. Allow the user to type in as many numbers as they want (one at a time) and end the program when they type in “0”. Use Horner’s method (given in step 3, below) to convert from binary to decimal.
Sample Run
Binary to Decimal Conversion Enter a binary string: 1101 1101 = 13 decimal Enter a binary string: 10011001 10011001 = 153 decimal
2
Enter a binary string: 1001001
1001001 = 73 decimal
Do the following
Within the loop, input a binary string (note there is no checking that the input is only 0’s and 1’s). Use input() NOT eval(input()). Return the string in binStr.
Initialize decimalValue to 0. This will hold the decimal value.
Using a for loop whose limit is the length of the binary string (len(binStr)), process each digit of the binary string as follows (Horner’s method): //
decimalValue = 0 for k in range(len(binStr)):
The next binary digit is binStr[k]. Call this digit. Multiply decimalValue by 2
Using the ord() function convert each binary digit (‘0’ or ‘1’) to its integer value by subtracting 48 from the ord() value (i.e. ord(digit)-48). Alternately you can use the int() function on each binary digit which does the same thing. Add the integer value of the digit to decimalValue.
Output the binary string and its decimal value as shown above.
##TELL ME WHAT IS WRONG WITH THE CODE
##IF YOU ARE SATISFIED WITH THE CODE, KINDLY LEAVE A LIKE, ELSE COMMENT TO CLEAR DOUBTS
CODE:
while True:
binStr = input("Enter a binary string: ")
if binStr == "0":
break
decimalValue = 0
for k in range(len(binStr)):
nextBinaryDigit = ord(binStr[k]) - 48
decimalValue *= 2
decimalValue += nextBinaryDigit
print(binStr,"=",decimalValue,"decimal\n")
OUTPUT:
Get Answers For Free
Most questions answered within 1 hours.