Java program for binary to hexadecimal conversion.



package demo;
import java.util.Scanner;
public class BinaryToHexadecimal
{
 public static void main(String[] args)
 {
  int[] hex = new int[1000];
  int i = 1, j = 0, rem, dec = 0, bin;
  Scanner sc = new Scanner(System.in);
  System.out.print("Enter a Binary Number: ");
  bin = sc.nextInt();
  while (bin > 0) {
   rem = bin % 2;
   dec = dec + rem * i;
   i = i * 2;
   bin = bin / 10;
  }
  /* At this state our input number is converted into Decimal Number */
  i = 0;
  while (dec != 0) {
   hex[i] = dec % 16;
   dec = dec / 16;
   i++;
  }
  System.out.print("Equivalent HexaDecimal value: ");
  for (j = i - 1; j >= 0; j--)
  {
   if (hex[j] > 9) 
   {
    System.out.print((char)(hex[j] + 55));
   } else
   {
    System.out.print(hex[j]);
   }
  }
 }
}

Output:
Enter a Binary Number: 11111100
Equivalent HexaDecimal value: FC
BUILD SUCCESSFUL (total time: 6 seconds)


No comments:

Post a Comment