(Printing the Decimal Equivalent of a Binary Number) Write an application that inputs an integer containing only 0s and 1s (i.e., a binary integer) and prints its decimal equivalent. [Hint: Use the remainder and division operators to pick off the binary number’s digits one at a time, from right to left. In the decimal number system, the rightmost digit has a positional value of 1 and the next digit to the left a positional value of 10, then 100, then 1000, and so on. The decimal number 234 can be interpreted as 4 * 1 + 3 * 10 + 2 * 100. In the binary number system, the rightmost digit has a positional value of 1, the next digit to the left a positional value of 2, then 4, then 8, and so on. The decimal equivalent of binary 1101 is 1 * 1 + 0 * 2 + 1 * 4 + 1 * 8, or 1 + 0 + 4 + 8 or, 13.]
Printing the Decimal Equivalent of a Binary Number in Java
/*
* Filename: BinaryToDecimal.java
*
* Description: Exercise 4.31 - Printing the Decimal Equivalent of a Binary
* Number
*
* @Author: Bilal Tahir Khan Meo
* Website: https://codeblah.com
*
* =====================================================================================
*/
import java.util.Scanner;
public class BinaryToDecimal{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int binary = 0; // original binary
int decimal = 0; // conversion
int place = 0; // the 2's place
System.out.print("Enter binary number for conversion: ");
binary = sc.nextInt();
while(binary != 0){
// extract rightmost digit
int lastDigit = binary % 10;
// raise rightmost digit to 2^place and add to decimal
decimal += lastDigit * Math.pow(2, place);
// slice rightmost digit from original
binary /= 10;
// shift 2's place to the left
place++;
}
System.out.printf("%d = %d\n", binary, decimal);
}
}