Hello,
The result is correct but not pass the task requirements.
I think i am missing some details
Error message:
Be sure that the toBinary(String) method correctly converts the string representation of a hexadecimal number to the string representation of a binary number.
Thank you.
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) {
//write your code here
String binary = new String();
String result = new String();
int decimal = 0;
//
if(binaryNumber==null || binaryNumber.isEmpty()){
return binary;
}
//
for(int i=0; i<binaryNumber.length();i++){
if(binaryNumber.charAt(i)!='0' && binaryNumber.charAt(i)!='1'){
return "messi";
}
}
while(binaryNumber.length() %4 != 0){
binaryNumber='0'+binaryNumber;
}
for(int i=0; i<binaryNumber.length(); i++) {
binary = binary + binaryNumber.charAt(i);
if(binary.length()==4){
for(int j=0; j<binary.length();j++){
decimal = decimal + (int) ( Character.getNumericValue(binary.charAt((binary.length()-1) - j)) * Math.pow(2,j));
//decimal=HEX.charAt(decimal);
}
binary="";
result+=HEX.charAt(decimal);
//result+=(int)decimal;
decimal=0;
}
}
return result;
}
public static String toBinary(String hexNumber) {
//write your code here
String binary = "";
String result = "";
char[] capital = {'A','B','C','D','E','F'};
int index = 0;
String temp = "";
if(hexNumber==null){
return "";
}
for(int i=0;i<hexNumber.length();i++){
for(int j=0;j<capital.length;j++){
if( hexNumber.charAt(i)==capital[j] ){
return result;
}
}
}
for (int i = 0; i < hexNumber.length(); i++) {
for (int j = 0; j < HEX.length(); j++) {
if (hexNumber.charAt(i) == HEX.charAt(j)) {
index=j;
//binary+=HEX.charAt(j);
while(index!=0){
temp=index%2+temp;
index=index/2;
}
while(temp.length()<4){
temp = 0+temp;
}
result+=temp;
temp="";
}
}
}
return result;
}
}