Computers and Technology

Question

Write a Java program that reads an 8-bit binary number from the keyboard as a string and then converts it into decimal. For example, if the input is “01001101”, the output should be “77”. (Hint: Break the string into substrings and then convert each substring to a value for a single bit (i.e., 0 or 1). If the bits from right to left are b0, b1, …, b7; the decimal equivalent value is b0 + 2b1 + 4b2 + 8b3 + 16b4 + 32b5 +64b6 + 128b7.

1 Answer

  • Answer:

    public class Brainly

    {

     public static void main(String[] args)

     {

       BinaryConverter conv = new BinaryConverter();

       String binStr = "01001101";

       System.out.print(binStr + " in decimal is "+conv.BinToDec(binStr));

     }

    }

    public class BinaryConverter

    {

     public int BinToDec(String binStr)

     {

       int d = 0;

       while(binStr.length() > 0)

       {

         d = (d << 1) + ((binStr.charAt(0) == '1') ? 1: 0);

         binStr = binStr.substring(1);

       }

       return d;

     }

    }

    Explanation:

    The program "eats" the string from left to right, and builds up the integer representation in variable "d" on the go. While there are digits left, it shifts the previous result to the left and sets the least signficant bit to 1 only if the corresponding string character is a 1.

NEWS TODAY