Here we are going to write a program on conversion of Binary To Hexadecimal Numbers in Java.

Binary To Hexadecimal Java Example :

ConvertBinaryToHexadecimal.java
import java.util.Scanner;

public class ConvertBinaryToHexadecimal {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("Enter any Binary Number : ");
String input = sc.nextLine();
convertBinaryToHexadecimal(input);
}

public static String convertBinaryToHexadecimal(String number) {
String hexa = "";
char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a',
'b', 'c', 'd', 'e', 'f' };
if (number != null && !number.isEmpty()) {
int decimal = convertBinaryToDecimal(number);
while (decimal > 0) {
hexa = hex[decimal % 16] + hexa;
decimal /= 16;
}
System.out.println("The hexa decimal number is: " + hexa);
}

return hexa;
}

public static int convertBinaryToDecimal(String number) {
int length = number.length() - 1;
int decimal = 0;
if (isBinary(number)) {
char[] digits = number.toCharArray();
for (char digit : digits) {
if (String.valueOf(digit).equals("1")) {
decimal += Math.pow(2, length);
}
--length;
}
System.out.println("The decimal number is : " + decimal);
}
return decimal;
}

public static boolean isBinary(String number) {

boolean isBinary = false;

if (number != null && !number.isEmpty()) {
long num = Long.parseLong(number);
while (num > 0) {
if (num % 10 <= 1) {
isBinary = true;
} else {
isBinary = false;
break;
}
num /= 10;
}
}

return isBinary;
}
}

Output :

Enter a Binary Number : 100110
The decimal number is : 38
The hexa decimal number is: 26

Happy Learning 🙂

Leave A Comment