# Printing the Decimal Equivalent of a Binary Number

(Printing the Decimal Equivalent of a Binary Number) Write a program 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.]

Solution:

`import java.util.Scanner;`

``` public class binary { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int bNumber,bNumberCopy,i=7,dNumber=0; int digit[] = new int; //String strBinaryNumber = "11011001"; ```

``` System.out.print("\nEnter binary number(max digits: 8) :"); bNumber = sc.nextInt(); if((Integer.toString(bNumber)).length() 0){ digit[i] = bNumberCopy % 10; bNumberCopy /= 10; i--; } for(int j=7;j>=0;j--){ dNumber += (Math.pow(2,(7-j))*digit[j]); } System.out.print("\nDecimal form of '" + bNumber + "' is :" + dNumber); }else{ System.out.print("\nInvalid input,,,,program terminates."); } } }```

Advertisements