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.");
}
}
}
About these ads
Categories: JAVA, Java SE Codes Tags: , , ,
  1. August 28, 2011 at 12:56 am | #1

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

  2. July 9, 2012 at 3:38 pm | #2

    what if it is a signed binary?

    • July 11, 2012 at 12:52 pm | #3

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

  3. April 6, 2013 at 6:24 pm | #4

    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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: