Q:

Java program to convert Binary Number into Decimal Number

belongs to collection: Java Most Popular & Searched Programs

0

Java program to convert Binary Number into Decimal Number

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

This program will read Binary value from the User and convert into its equivalent Decimal Number in Java. It is an example of Binary to Decimal conversion in Java.

package com.includehelp;

import java.util.Scanner;

/**
 * Program to convert a given binary number to Decimal format
 * @author includehelp
 */
public class BinaryToDecimal {
    
    /**
     * to check is given number is binary number or not
     * @param binaryNmber
     * @return 
     */
    public static boolean isBinaryNumber(long binaryNmber) {
        while (binaryNmber >0) {
            if (binaryNmber % 10 > 1) {
                return false;
            }
            binaryNmber = binaryNmber / 10;
        }
        return true;
    }

    /**
     * Method to get Decimal number from input binary number
     * @param binaryNmber
     * @return 
     */
    static int getDecimalNumber(long binaryNmber){
        int decomalNo = 0;
        int power=0;
        while(binaryNmber>0){
            long r       =binaryNmber%10;
            decomalNo   =(int) (decomalNo + ( r*Math.pow(2, power) ) );
            binaryNmber = binaryNmber/10;
            power++;
        }
        return  decomalNo; 
    }
    
    public static void main(String[] arg){
        Scanner sc  =   new Scanner(System.in);
        System.out.println("Enter Binary Number  : ");
        long binaryNmber =   sc.nextLong();
        
        if(isBinaryNumber(binaryNmber)){
            int decimalNumber = getDecimalNumber(binaryNmber);
            System.out.println("Decimal Number : "+decimalNumber);
        }
        else{
            System.out.println("Number is not Binary");
        }
    }
    
}

Output

Enter Binary Number  : 
1010101101010011
Decimal Number : 43859

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to convert Decimal Number into Binary... >>
<< Java program to check whether given number is Arms...