my code converts binary into hexadecimal. I pass an array that contains a string 0s and 1s to the function and it converts it to a string of characters that represent the hexadecimal value. The string is then printed. So for example for a string "01000000010000110111000000100000" it would output "40 43 70 20". My problem is that it works properly up to the last 0 and after that for some reason it prints some mess as well as an original array that was passed. Here is my code:
Code:
#include <stdio.h>
#include <string.h>
int hex_convert (char array[33], char final[10])
{
int i, n, j = 0;
int k;
char temp[5];
for (n = 0; n < 32; n = n + 4)
{
for (i = n; i < (n + 4); i++)
{
temp[j] = array[i];
j++;
}
j = 0;
if (strcmp ("0000", temp) == 0){
final[strlen(final)] = '0';
}else if (strcmp ("0001", temp) == 0){
final[strlen(final)] = '1';
}else if (strcmp ("0010", temp) == 0){
final[strlen(final)] = '2';
}else if (strcmp ("0011", temp) == 0){
final[strlen(final)] = '3';
}else if (strcmp ("0100", temp) == 0){
final[strlen(final)] = '4';
}else if (strcmp ("0101", temp) == 0){
final[strlen(final)] = '5';
}else if (strcmp ("0110", temp) == 0){
final[strlen(final)] = '6';
}else if (strcmp ("0111", temp) == 0){
final[strlen(final)] = '7';
}else if (strcmp ("1000", temp) == 0){
final[strlen(final)] = '8';
}else if (strcmp ("1001", temp) == 0){
final[strlen(final)] = '9';
}else if (strcmp ("1010", temp) == 0){
final[strlen(final)] = 'A';
}else if (strcmp ("1011", temp) == 0){
final[strlen(final)] = 'B';
}else if (strcmp ("1100", temp) == 0){
final[strlen(final)] = 'C';
}else if (strcmp ("1101", temp) == 0){
final[strlen(final)] = 'D';
}else if (strcmp ("1110", temp) == 0){
final[strlen(final)] = 'E';
}else if (strcmp ("1111", temp) == 0){
final[strlen(final)] = 'F';
}
}
return 0;
}
int main (void)
{
char array[33] = "01000000010000110111000000100000";
char final[10];
hex_convert (array, final);
printf ("%s\n", final);
return 0;
}
and it outputs:
Code:
4043702??010000000100001101110000001000000
I double checked that I allocated enough space for the final string and everything seems fine. I can't figure out where it goes wrong