Binary To Hexadecimal Conversion Java Program

By | 2018-03-21T21:13:20+00:00 June 19th, 2016|java programs|0 Comments

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

Binary To Hexadecimal Java Example :

import java.util.Scanner;

public class ConvertBinaryToHexadecimal {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter any Binary Number : ");
        String input = sc.nextLine();
        convertBinaryToHexadecimal(input);
    }

    public static String convertBinaryToHexadecimal(String number) {
        String hexa = "";
        char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
                'b', 'c', 'd', 'e', 'f' };
        if (number != null && !number.isEmpty()) {
            int decimal = convertBinaryToDecimal(number);
            while (decimal > 0) {
                hexa = hex[decimal % 16] + hexa;
                decimal /= 16;
            }
            System.out.println("The hexa decimal number is: " + hexa);
        }

        return hexa;
    }

    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("The decimal number is : " + decimal);
        }
        return decimal;
    }

    public static boolean isBinary(String number) {

        boolean isBinary = false;

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

        return isBinary;
    }
}

Output :

Enter a Binary Number : 100110
The decimal number is : 38
The hexa decimal number is: 26

Happy Learning 🙂

About the Author:

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+ ,

Leave A Comment