Home Java Java-conversion Convert Binary to Hexadecimal
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Convert Binary to Hexadecimal

Advertisement
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.". 

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 != && 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);
  }
}

Download this program.

Output of this program:

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

C:\corejava>_

 

Advertisements

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 31, 2007

Ask Questions?    Discuss: Convert Binary to Hexadecimal   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
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
DMCA.com