63.5k views
13 votes
Write a program named BinaryToDecimal.java 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, b3, then decimal equivalent is 8b0 4b1 2b2 b3)

1 Answer

10 votes

Answer:

import java.util.*;

public class BinaryToDecimal

{

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String binaryNumber;

int decimalNumber = 0;

System.out.print("Enter the binary number: ");

binaryNumber = input.nextLine();

for(int i=0; i<binaryNumber.length(); i++){

char c = binaryNumber.charAt(binaryNumber.length()-1-i);

int digit = Character.getNumericValue(c);

decimalNumber += (digit * Math.pow(2, i));

}

System.out.println(decimalNumber);

}

}

Step-by-step explanation:

Create a Scanner object to be able to get input from the user

Declare the variables

Ask the user to enter the binaryNumber as a String

Create a for loop that iterates through the binaryNumber. Get each character using charAt() method. Convert that character to an integer value using Character.getNumericValue(). Add the multiplication of integer value and 2 to the power of i to the decimalNumber variable (cumulative sum)

When the loop is done, print the decimalNumber variable

User Honza Hejzl
by
6.8k points