how to do binary to hexadecimal code example

Example 1: hexadecimal to binary in java

import java.util.Scanner;
public class HexadecimalToBinaryJava
{
   public static void main(String[] args)
   {
      int decimalNumber, a = 1, b;
      int[] binaryNumber = new int[100];
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter hexadecimal number: ");
      String hexaDecimalNumber = sc.nextLine();
      // converting hexadecimal to decimal number
      decimalNumber = toDecimal(hexaDecimalNumber);
      // converting decimal number to binary number
      while(decimalNumber != 0)
      {
         binaryNumber[a++] = decimalNumber % 2;
         decimalNumber = decimalNumber / 2;
      }
      System.out.print("The equivalent binary number is: ");
      for(b = a - 1; b > 0; b--)
      {
         System.out.print(binaryNumber[b]);
      }
      System.out.print("\n");
      sc.close();
   }
   public static int toDecimal(String str)
   {
      String strDigits = "0123456789ABCDEF";
      str = str.toUpperCase();
      int val = 0;
      for(int a = 0; a < str.length(); a++)
      {
         char c = str.charAt(a);
         int d = strDigits.indexOf(c);
         val = 16 * val + d;
      }
      return val;
   }
}

Example 2: binary to hexadecimal in java

import java.util.Scanner;
public class BinaryToHexadecimalJava
{
   public static void main(String[] args)
   {
      int[] hexaDecimal = new int[1000];
      int a = 1, b = 0, r, decimal = 0, binary;
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter binary number: ");
      binary = sc.nextInt();
      while(binary > 0)
      {
         r = binary % 2;
         decimal = decimal + r * a;
         a = a * 2;
         binary = binary / 10;
      }
      a = 0;
      while(decimal != 0)
      {
         hexaDecimal[a] = decimal % 16;
         decimal = decimal / 16;
         a++;
      }
      System.out.print("Equivalent hexadecimal value is: ");
      for(b = a - 1; b >= 0; b--)
      {
         if(hexaDecimal[b] > 9)
         {
            System.out.print((char)(hexaDecimal[b] + 55) + "\n");
         }
         else
         {
            System.out.print(hexaDecimal[b] + "\n");
         }
      }
      sc.close();
   }
}

Tags:

Java Example