Write a program that reads a 4-bit binary number from the keyboard as a string and then converts it into decimal. For example, if the input is 1100, the output should be 12. (Hint: Break the string into substrings and then convert each substring to a value for a single bit. If the bits are b0, b1, b2, and b3, the decimal equivalent is 8b0+ 4b1+ 2b2+ b3.)

Respuesta :

Answer:

import java.util.Scanner;

public class ss11{

       public static void main (String[]args) {

             Scanner keyboard = new Scanner (System.in)

             String a1, a2, a3, a4, a5;

              int i1, i2, i3, i4, i5;

              System.out.println("Enter a four bit binary number:");

               a1= keyboard.next();

               a2= a1.substring(0,1);

               a3= a1.substring(1,2);

               a4= a1.substring(2,3);

               a5= a1.substring(3,4);

                i1 = Integer.parseInt(a2);

                i2 = Integer.parseInt(a3);

                i3 = Integer.parseInt(a4);

                i4 = Integer.parseInt(a5);

                i1= i1 * 8;

                i2= i1 * 4;

                i3= i1 * 2;

                i4= i1 * 1;

                i5= i1+i2+i3+i4;

                System.out.println("The converted decimal number is: +i5);

}

}

Explanation:

The program is a sequential program, and does not require loops or conditional statements

The program in Python, where comments are used to explain each line is as follows:

#This gets input for the binary digit

bitNum = input()

#This calculates the decimal equivalent of the binary digit

dec_Num = int(bitNum[0]) * 8 +int(bitNum[1]) * 4 + int(bitNum[2]) * 2 + int(bitNum[3]) * 1

#This prints the decimal equivalent of the binary digit

print(dec_Num)

Read more about sequential programs at:

https://brainly.com/question/17970226

ACCESS MORE