Ask Question
17 August, 08:39

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

+1
Answers (1)
  1. 17 August, 10:27
    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?
Find 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 and Technology if you're in doubt about the correctness of the answers or there's no answer, then try to use the smart search and find answers to the similar questions.
Search for Other Answers