Ask Question
10 April, 07:04

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

+3
Answers (1)
  1. 10 April, 09:39
    0
    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))

    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
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Write a program that prompts the user to enter a four binary numbers as a string and displays its corresponding decimal value. Here are ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers