opc0de
opc0de

Reputation: 11768

Convert array of bytes to hexadecimal string in plain old C

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 ?

Upvotes: 1

Views: 7106

Answers (2)

JeremyP
JeremyP

Reputation: 86651

You have 10 bytes in your array, so your buffer needs at least 21 bytes (2 hex digits are needed for each byte + 1 for the null terminator).

I don't understand what you are doing here:

sprintf(&asta[k],"%X",buffer[4 + k]);

Why are you starting with the fifth byte in the buffer? Also, each byte in your buffer takes two bytes in the string, so you need to print to asta[2 * k].

Putting it together you get something like:

char * asta = (char*)calloc(2 * sizeof buffer + 1, sizeof(char)); // calloc automatically zeros asta
int k;
for (k = 0; k < sizeof buffer ; k++)
{
    sprintf(&asta[2 * k],"%02X", (unsigned int)buffer[k]); // Not sure if the cast is needed
}
printf("%s",asta);

Upvotes: 4

Some programmer dude
Some programmer dude

Reputation: 409176

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.

Upvotes: 1

Related Questions