What would be the best way to go above converting from an integer array representing the bits of a number to hexadecimal?
My current attempt reads four bits at a time then tries to print the corresponding hex character, but I dont see to get any output.
Here is what I have:
/**
* Maps a 4 bit string in binary to the corresponding
* hex digit
*/
void map_bin_to_hex(char *c)
{
printf("In mapbin: C = %s\n", c); //This is printing funny output
if(!strcmp(c, "0000")) printf("0");
else if(!strcmp(c, "0001")) printf("1");
else if(!strcmp(c, "0010")) printf("2");
else if(!strcmp(c, "0011")) printf("3");
else if(!strcmp(c, "0100")) printf("4");
else if(!strcmp(c, "0101")) printf("5");
else if(!strcmp(c, "0110")) printf("6");
else if(!strcmp(c, "0111")) printf("7");
else if(!strcmp(c, "1000")) printf("8");
else if(!strcmp(c, "1001")) printf("9");
else if(!strcmp(c, "1010")) printf("A");
else if(!strcmp(c, "1011")) printf("B");
else if(!strcmp(c, "1100")) printf("C");
else if(!strcmp(c, "1101")) printf("D");
else if(!strcmp(c, "1110")) printf("E");
else if(!strcmp(c, "1111")) printf("F");
}
/**
* Reads 4 array elements at a time, passing them to map_bin_to_hex
*/
void bin_array_to_hex(int *b, int length)
{
int i, j, k;
//read 4 bits 16 times
for(i = 0; i < 64; i+=4)
{
char hexB[4];
for(k = 0, j = i; j < (i+4); j++, k++)
{
hexB[k] = b[j];
printf("h[%d] = %d\n", k, hexB[k]);
}
map_bin_to_hex(hexB);
}
printf("\n");
}
int main()
{
// a 64-bit number represented as an array of bits
int x[] =[1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,1,0,0,1,1,1,1,1,1,1,1,
1,1,1,1,0,0,0,0,1,0,1,0,1,0,1,0,1,1,1,1,0,0,0,0,1,0,1,0,0,0,1,0];
bin_array_to_hex(x, 64);
}
The bin_array_to_hex() function reads the array in 4bit sections then passes those to map_bin_to_hex(), the output from bin_array_to_hex() is is correct, but something is wrong with my mapping function.
Any help would be appreciated.
EDIT: New Solution
void map_bin_to_hex(char *c)
{
char hexMap[] =
{'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
int index = strtoull(c, NULL, 2);
printf("%c", hexMap[index]);
}
You are almost there,
replace
with
Also,
char hexB[4];needs to bechar hexB[5];(last char is for null termination; don’t forget to sethexB[4]='\0';before callingmap_bin_to_hex).Once you’re done with this initial fix, take a look at other solutions available on the internet: you will see how to do the whole thing in five or six lines.
EDIT As an additional challenge, see if you can use these two string constants to avoid the long chain of if-then-else statements in your first method:
Hint: observe how the first string is exactly four times longer than the second one.