17.7k views
2 votes
Write a program that prompts the user to enter a four binary numbers as a string and displays its corresponding decimal value. Here are sample runs: Enter a four-digit binary string: 1111 The decimal number for 1111 is 15

User Amighty
by
5.8k points

1 Answer

1 vote

Answer:

binary_string = input("Enter a four-digit binary string: ")

decimal_number = 0

count = len(binary_string) - 1

for d in binary_string:

decimal_number += int(d) * 2**count

count -= 1

print("The decimal number for " + binary_string + " is " + str(decimal_number))

Step-by-step explanation:

*The code is in Python.

Ask the user to enter a four-digit binary string, binary_string

Initialize the decimal_number as 0 to hold the decimal value

Initialize the count as the length of the string - 1 (In this case, it is equal to 3)

Create a for loop that iterates through the binary_string. Inside the loop, for each character in binary_string get the integer of the character (use int()) and multiply it by 2 to the power of count. Add this value to the decimal_number cumulatively. Decrease the count by 1.

When the loop is done, print the decimal_number

User Psypher
by
6.5k points