Ask 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 sample runs: Enter a four-digit binary string: 1111 The decimal number for 1111 is 15

+2
Answers (1)
  1. 9 March, 06:07
    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 & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers