Tutorials

In this section, you will learn to convert binary data into hexadecimal.

In this section, you will learn to convert binary data into hexadecimal.

In this section, you will learn to convert binary data into hexadecimal.  The java.lang package provides the functionality to convert the binary data into hexadecimal.

Description of the program:

This program takes a binary data from user, which is a string type that is  converted into the long data using the parseLong() method. It takes string type value and converts it into a long data. The condition [ if(rem != 0 && rem != 1) ] checks whether the given number is binary number or not. If the given number is either '0' or '1' , program converts the binary data into hexadecimal using toHexaString() method. If fails, it displays a message "This is not a binary number" or "Please try once again.".

toHexString():
This is the method that takes an integer type value and converts it into binary to hexadecimal. The base of hexadecimal is 16.

Here is the code of this program:

 ``` import java.io.*; import java.lang.*; public class  BinaryToHexa{   public static void main(String[] args)throws IOException{   BufferedReader bf= new BufferedReader(new InputStreamReader(System.in));   System.out.println("Enter the Binary number:");   String hex = bf.readLine();   long num = Long.parseLong(hex);   long rem;   while(num > 0){   rem = num % 10;   num = num / 10;   if(rem != 0 && rem != 1){   System.out.println("This is not a binary number.");   System.out.println("Please try once again.");   System.exit(0);   }   }   int i= Integer.parseInt(hex,2);   String hexString = Integer.toHexString(i);   System.out.println("Hexa decimal: " + hexString);   } }```

`Output of this program:`