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

run:
Enter the Binary number:
101010
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 ...
HOW TO CONVERT BINARY TO DECIMAL ...
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

Comments

Post a Comment