I am looking into a method to convert a byte array to a hexadecimal string here is what i coded :
unsigned char buffer[] = {0xAA,0xBB,0x01,0xAB,0x11,0x12,0x13,0x22,0x11,0x14};
int _tmain(int argc, _TCHAR* argv[])
{
char * asta = (char*)malloc(16);
memset(asta,0,16);
int k;
for (k = 0; k < 16 ; k++)
{
sprintf(&asta[k],"%X",buffer[4 + k]);
}
printf("%s",asta);
_getch();
}
Only the first byte is converted correctly the rest are not. How can i fix the code ?
You have to remember that two-digit hexadecimal numbers will still be two digits when you print it as a string, i.e. it will take up two characters.
In the loop, the second iteration will overwrite the second character of the string, the third iteration will overwrite the third characters, etc.
Also, since each two-digit number will use two characters, you must allocate memory for 32 characters, plus one for the string terminating
'\0'character.And as noted in the comments, you are accessing data outside of your array.