the toBinary(String) method contains any character other than digits from 0 to 9 or lowercase Latin letters from a to f, then the method returns an empty string.
package en.codegym.task.pro.task09.task0908;
/*
Binary to hexadecimal converter
*/
public class Solution {
private static final String HEX = "0123456789abcdef";
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) {
if(binaryNumber==null|| binaryNumber.isEmpty())
{
return "";
}
for(int i=0;i<binaryNumber.length()-1;i++)
{
if(binaryNumber.charAt(i)=='0' || binaryNumber.charAt(i)=='1')
{
continue;
}
else {
return"";
}
}
if (binaryNumber.length()%4!=0)
{
int degits=4-(binaryNumber.length()%4);
for(int i=0;i<degits;i++)
{
binaryNumber='0'+binaryNumber;
}
}
int k=0;
int temp=0;
String hexNo="";
while(k < binaryNumber.length()-1) //(binary.length()/4)
{
String t= binaryNumber.substring(k,k+4);
int decNo=0;
for(int j=0;j<t.length();j++)
{
temp=Character.getNumericValue(t.charAt((t.length()-1)-j));
decNo=(int) (decNo+(temp*(Math.pow(2, j))));
}
hexNo=hexNo+(HEX.charAt(decNo));
k=k+4;
}
return hexNo;
}
public static String toBinary(String hexNumber) {
if(hexNumber==null|| hexNumber.isEmpty())
{
return "";
}
return null;
}
}