Tuesday, April 30, 2013

How to Convert from binary to hex in java

Simple One line code to convert String containing a binary value to Hex

String bin = Integer.toHexString(Integer.parseInt(binOutput, 2));

Full Code for conversion

import java.io.*;
import java.lang.*;

public class  BinaryToHexadecimal{
  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.");
  int i= Integer.parseInt(hex,2);
  String hexString = Integer.toHexString(i);
  System.out.println("Hexa decimal: " + hexString);

Enter the Binary number:
Hexa decimal: 2a

java - Translating a String containing a binary value to Hex
java - efficiently converting hex to binary
Binary to Hexadecimal Conversion w/o using predefined functions
Convert from binary to hex in java?
Convert binary to hex java programming?
Java program to convert binary,octal,decimal to ...
Write a program in java to convert binary numbers ...
Convert Hexadecimal To Binary Using Java 
How to convert Hexadecimal to Decimal, Binary and Octal in Java

Converting binary to hex, any tips on how to do this?

String containing a binary value to Hex