ADVERTISEMENT
ADVERTISEMENT

Java program to convert Binary Number into Decimal Number

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

Java Most Popular & Searched Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.