Leah Greenstein Leah Greenstein - 4 months ago 31
C Question

hex to binary converter in C not working

I am trying to first convert the hex string to binary, but it is not working. I know there is a better way to do it other than a switch statement (with bitshifting I think?). If you could explain how this works too, if you understand it, I would really appreciate it. Regarding my switch statement, it raises some numbers to the power of 3. Can you please tell me why this is happening?

#include <stdio.h>

int toBinary(char c1){
switch (c1)
{
case '0':
return(0000); break;
case '1':
return(0001); break;
case '2':
return(0010); break;
case '3':
return(0011); break;
case '4':
return(0100); break;
case '5':
return(0101); break;
case '6':
return(0110); break;
case '7':
return(0111); break;
case '8':
return(1000); break;
case '9':
return(1001); break;
case 'A':
return(1010); break;
case 'B':
return(1011); break;
case 'C':
return(1100); break;
case 'D':
return(1101); break;
case 'E':
return(1110); break;
case 'F':
return(1111); break;
case 'a':
return(1010); break;
case 'b':
return(1011); break;
case 'c':
return(1100); break;
case 'd':
return(1101); break;
case 'e':
return(1110); break;
case 'f':
return(1111); break;
default:
printf("\n Invalid hexa digit %c ");
return 0;
}
}

int main(){
char hex[] = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
char check[] = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
int i = 0;
for(i; i <sizeof(hex); i+=3){
char c1 = hex[i];
char c2 = hex[i+1];
char c3 = hex[i+2];
int c11 = toBinary(c1);
int c22 = toBinary(c2);
int c33 = toBinary(c3);
printf("%d \n",c11);
printf("%d \n",c22);
printf("%d \n",c33);
}
return 0;
}

Answer

The values you're returning are not binary as you think they are. Numeric constants starting with 0 are octal (base 8), while constants starting with 1-9 are decimal.

So 0010 is actually 8 in octal, not 2, while 1000 is one thousand, not 8.

You can return the decimal values in your switch:

switch (c1)
    {
    case '0':
        return 0;     // no need to break if there is a return
    case '1':
        return 1;
    case '2':
        return 2;
    ...

Or, you can just subtract the ASCII value of 0 or A as appropriate:

if (c1 >= '0' && c1 <= '9') {
    return c1 - '0';
} else if (c1 >= 'A' && c1 <= 'F') {
    return c1 - 'A' + 10;
} else {
    printf("\n Invalid hexa digit %c ", c1);   // don't forget to pass c1 to print it
    return 0;
}
Comments