Convert Binary to Hexadecimal

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

Convert Binary to 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.". 

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.lang.*;

public class  BinaryToHexa{
  public static void main(String[] args)throws IOException{
  BufferedReader bf= new BufferedReader(new InputStreamReader(;
  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 != && rem != 1){
  System.out.println("This is not a binary number.");
  System.out.println("Please try once again.");
  int i= Integer.parseInt(hex,2);
  String hexString = Integer.toHexString(i);
  System.out.println("Hexa decimal: " + hexString);

Download this program.

Output of this program:

C:\corejava>java BinaryToHexa
Enter the Binary number:
Hexa decimal: 7f






We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

Convert Binary to Hexadecimal

Posted on: May 31, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Convert Binary to Hexadecimal   View All Comments

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Parita Vora
October 19, 2011
binary to hexadecimal

I want code for how to convert binary to hexadecimal in c language using function concept in easy way.
kishore reddy
February 12, 2012
programs logics

this is ok