I'll admit this isn't the most elegant solution, but it works perfectly in IDE, including with binary numbers whose lengths are not multiples of 4. When I try to validate in CodeGym, though, I get a "String index 0 out of range" error in the toHex method, which shouldn't be possible.
package en.codegym.task.pro.task09.task0908;
/*
Binary to hexadecimal converter
*/
public class Solution {
public static void main(String[] args) {
String binaryNumber = "100111010000";
System.out.println("Binary number " + binaryNumber + " is equal to hexadecimal number " + toHex(binaryNumber));
String hexNumber = "9d0";
System.out.println("Hexadecimal number " + hexNumber + " is equal to binary number " + toBinary(hexNumber));
}
public static String toHex(String binaryNumber) {
String hex = "0123456789abcdef";
while (binaryNumber.length() % 4 != 0) {
binaryNumber = 0 + binaryNumber;
}
if (binaryNumber == "" || binaryNumber == null) {
return "";
}
int b = 0;
b += (binaryNumber.charAt(0)-'0') * 8;
b += (binaryNumber.charAt(1)-'0') * 4;
b += (binaryNumber.charAt(2)-'0') * 2;
b += (binaryNumber.charAt(3)-'0');
return hex.charAt(b) + toHex(binaryNumber.substring(4));
}
public static String toBinary(String hexNumber) {
String hex = "0123456789abcdef";
if (hexNumber == "" || hexNumber == null) {
return "";
}
String bin = "";
int n = hex.indexOf(Character.toString(hexNumber.charAt(0)));
if (n>7) {
bin += 1;
n -= 8;
}
else {
bin += 0;
}
if (n>3) {
bin += 1;
n -= 4;
}
else {
bin += 0;
}
if (n>1) {
bin += 1;
n -= 2;
}
else {
bin += 0;
}
bin += n;
return bin + toBinary(hexNumber.substring(1));
}
}