codescracker


java

Java Program to Convert Hexadecimal to Binary



« Previous Program Next Program »


Convert Hexadecimal to Binary

To convert hexadecimal to binary in Java Programming, you have to ask to the user to enter any number in hexadecimal number format to convert it into binary number format to display the equivalent value in binary number system as shown in the following program.

Java Programming Code to Convert Hexadecimal to Binary

Following Java Program ask to the user to enter any number in hexadecimal to convert it into binary, then display the result on the screen:

/* Java Program Example - Convert Hexadecimal to Binary */
		
import java.util.Scanner;

public class JavaProgram
{
    public static int hex2decimal(String s)
    {
             String digits = "0123456789ABCDEF";
             s = s.toUpperCase();
             int val = 0;
             for (int i = 0; i < s.length(); i++)
             {
                 char c = s.charAt(i);
                 int d = digits.indexOf(c);
                 val = 16*val + d;
             }
             return val;
    }
    public static void main(String args[])
    {
        String hexdecnum;
        int decnum, i=1, j;
        int binnum[] = new int[100];
        Scanner scan = new Scanner(System.in);
		
        System.out.print("Enter Hexadecimal Number : ");
        hexdecnum = scan.nextLine();
        
        /* first convert the hexadecimal to decimal */
        
        decnum = hex2decimal(hexdecnum);
        
        /* now convert the decimal to binary */
        
        while(decnum != 0)
        {
            binnum[i++] = decnum%2;
            decnum = decnum/2;
        }
		
        System.out.print("Equivalent Binary Number is :\n");
        for(j=i-1; j>0; j--)
        {
            System.out.print(binnum[j]);
        }
    }
}

When the above Java Program is compile and executed, it will produce the following output:

Java Program convert hexadecimal to binary

Same Program in Other Languages

You may also like to learn and practice the same program in other popular programming languages:


« Previous Program Next Program »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test