i wrote a program to convert a hexadecimal number to its equivalent binary form using the following code but i got wrong results. The code is as follows:
public String convert(String num){
String res="";
int []hex={0000,0001,0010,0011,0100,0101,0110,0111,1000,1001,1010,1011,1100,1101,1110,1111};
int i;
char ch;
for(i=0;i<num.length();i++)
{
ch=num.charAt(i);
if(ch>='a' && ch<='f'){
res+=hex[ch-97+10]+"";
}
else if(ch>='A' && ch<='F'){
res+=hex[ch-65+10]+"";
}
else if(ch>='0' && ch<='9'){
int d=ch-48;
res+=hex[d]+"";
}
}
return res;
}
If i give the sample input as “12ae” then i get the corresponding output as “1810101110”.
It happens only(goes wrong) when there is a number in the input field and works fine for all characters only. But when i change the array named hex to that of a String type it gives me the exact answer.
Is it because the compiler treats the numbers in the integer array as some form of octal numbers or is it because of some other reason?
You’re on the right track with the octal numbers. The following declaration:
declares an array of integers that in words, would be
and so on. This is clearly not what you want. If you declare
hexasString[] hex, and use"0000","0001",..., then you will get the intended answer.