Home > JAVA, Java SE Codes > BINARY TO DECIMAL – Java Program

BINARY TO DECIMAL – Java Program

Question: [BINARY TO DECIMAL]
Write an application that inputs an integer containing only 0’s and 1’s (i.e. a binary integer) and prints its decimal equivalent. [Hint: Use the reminder 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 has 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 has 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].
Answer

/**
* FileName: BinaryToDecimal.java
* @author (Sandeep Negi)
* MCA 2nd Year
* Java Programming Lab-406
*/

import java.util.Scanner;

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

System.out.print("\nEnter binary number(max digits: 8) :");
bNumber = sc.nextInt();
if((Integer.toString(bNumber)).length() <= 8){
bNumberCopy = bNumber;
while(bNumberCopy > 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.");
}
}
}
Categories: JAVA, Java SE Codes Tags: , , ,
  1. August 28, 2011 at 12:56 am

    I liked your article is an interesting technology
    thanks to google I found you

  2. July 9, 2012 at 3:38 pm

    what if it is a signed binary?

    • July 11, 2012 at 12:52 pm

      This solution works only or +ve integers means Unsigned Integers.

  3. April 6, 2013 at 6:24 pm

    If you desire to increase your familiarity just keep visiting
    this web page and be updated with the most up-to-date news update posted here.

  1. No trackbacks yet.

Leave a reply to Retsehc Nhoj Oelce Cancel reply