Write a program to convert Binary to Hexadecimal number system


This Java program takes a binary number as input from the user, converts it to decimal and then converts the decimal number to hexadecimal.

  • The program first declares an integer array hex to store the hexadecimal digits. Then it initializes variables i and j to 1 and 0 respectively, rem to store the remainder of binary division, dec to store the decimal equivalent of the binary number, and bin to store the input binary number entered by the user.
  • The program prompts the user to enter a binary number and then reads it using the Scanner class. It then enters a loop that performs binary to decimal conversion using the traditional method of multiplying each digit by 2 raised to a power of increasing value, and then adding up the products. The loop keeps updating the decimal equivalent dec and the power i until the binary number becomes 0.
  • Next, the program enters another loop that performs decimal to hexadecimal conversion. It uses the modulo operator % to obtain the remainder of division of the decimal equivalent dec by 16, and stores it in the hex array at index i. It then updates the decimal equivalent dec and the index i. The loop continues until the decimal equivalent becomes 0.
  • Finally, the program prints the hexadecimal equivalent of the binary number by iterating over the hex array in reverse order starting from index i-1, which is the last index used to store a digit. For each digit, it checks if it is greater than 9. If so, it converts it to the corresponding uppercase letter using ASCII code, by adding 55 to it. Otherwise, it prints the digit as it is.

Note that the program prints a newline character "\n" after each digit, which causes the output to be printed vertically instead of horizontally. If you want to print the output horizontally, you can remove the "\n" from the System.out.print() statements.

Source Code

import java.util.Scanner;
class Binary_Hexadecimal
{
	public static void main(String[] args) 
	{
		int[] hex = new int[1000];
		int i = 1, j = 0, rem, dec = 0, bin;
		Scanner input = new Scanner(System.in);
		System.out.print("Enter The Binary Number : ");
		bin = input.nextInt();
		System.out.println("Binary Number : " + bin);
		while (bin > 0)
		{
			rem = bin % 2;
			dec = dec + rem * i;
			i = i * 2;
			bin = bin / 10;
		}
		i = 0;
		while (dec != 0)
		{
			hex[i] = dec % 16;
			dec = dec / 16;
			i++;
		}
		System.out.print("HexaDecimal Number : ");
		for (j = i - 1; j >= 0; j--)
		{
			if (hex[j] > 9)
				System.out.print((char)(hex[j] + 55)+"\n");
			else
				System.out.print(hex[j]+"\n");
		}
	}
}
 

Output

Enter The Binary Number : 1010
Binary Number : 1010
HexaDecimal Number : A

Example Programs