Tuesday , February 28 2017
Home / java programs / Binary To Decimal Conversion Java Program

Binary To Decimal Conversion Java Program

Here we are going to write a program on conversion of Binary to Decimal Numbers in Java.

Binary To Decimal Conversion :


import java.util.Scanner;

public class ConvertBinaryToDecimal {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any Binary Number : ");
        String input = sc.nextLine();
        convertBinaryToDecimal(input);
    }

    public static int convertBinaryToDecimal(String number) {
        int length = number.length() - 1;
        int decimal = 0;
        if (isBinary(number)) {
            char[] digits = number.toCharArray();
            for (char digit : digits) {
                if (String.valueOf(digit).equals("1")) {
                    decimal += Math.pow(2, length);
                }
                --length;
            }
            System.out.println("Decimal Number is : " + decimal);
        }
        return decimal;
    }

    public static boolean isBinary(String number) {

        boolean isBinary = false;

        if (number != null && !number.isEmpty()) {
            int num = Integer.parseInt(number);
            while (num > 0) {
                if (num % 10 <= 1) {
                    isBinary = true;
                } else {
                    isBinary = false;
                    break;
                }
                num /= 10;
            }
        }

        return isBinary;
    }

}

Output :

Enter a Binary Number : 1011101
The decimal number is : 93

About chandrashekhar

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Check Also

Java Program to Find the GCD of Two Numbers

Here we are going to find GCD of two numbers in Java. Find GCD of two …

Leave a Reply

Your email address will not be published. Required fields are marked *