SIMPLE ONE LINE CODE TO CONVERT STRING CONTAINING A BINARY VALUE TO HEX
String bin = Integer.toHexString(Integer.parseInt(binOutput, 2));
//when integer size exceeds use Long instead of Integer
String bin = Long .toHexString(Long .parseLong(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
----------------------------------------------
No comments:
Post a Comment