Binary to HexaDecimal in java

Let’s learn binary to hexadecimal in java.

Binary to HexaDecimal in java

To convert binary to hexadecimal first get input from user using nextLine() method of Scanner class. Meanwhile parse user input using Integer.parseInt(String s, int radix) method and store this value in integer variable ‘number’.

Integer.parseInt(String s, int radix) method parses the string argument as a signed integer in the radix specified by the second argument.

In the next step this parsed value is then passed as an argument to Integer.toHexString() method. This method returns the string representation of the unsigned integer value represented by the argument in hexadecimal (base 16).

Finally print hexadecimal value on console. Here’s the program to convert binary to hexadecimal.

import java.util.Scanner;
public class BinaryToHexadecimalJava
{
   public static void main(String[] args) 
   {
      int number;
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter number to convert binary to hexadecimal: ");
      number = Integer.parseInt(sc.nextLine(), 2);
      String strHexadecimal = Integer.toHexString(number);
      System.out.println("HexaDecimal value is: " + strHexadecimal);
      sc.close();
   }
}

Output:

Please enter number to convert binary to hexadecimal:
101011011111
HexaDecimal value is: adf

Please enter number to convert binary to hexadecimal:
101010011110
HexaDecimal value is: a9e


Also read – major features of java