1

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 ?

opc0de
  • 11,557
  • 14
  • 94
  • 187
  • 3
    `buffer` has only 10 elements, you're accessing out of bounds. – Daniel Fischer Jun 18 '12 at 11:03
  • 3
    1. 16 bytes is not enough for 10 hexadecimal numbers; 2. you never free the memory; 3. every hexadecimal number needs 2 bytes. – pmg Jun 18 '12 at 11:04
  • @DanielFischer the code doesn't work from other reasons if you point me to the right direction i will be able to modify it. I don't think i use sprintf good! – opc0de Jun 18 '12 at 11:08

2 Answers2

4

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);
JeremyP
  • 84,577
  • 15
  • 123
  • 161
1

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Also, he should do the conversion using the format string "%02X" instead of %X , otherwise there will be some bytes that is converted to hex with only one digit, which will be a problem when you want to convert from hex to binary again. – nos Jun 18 '12 at 11:19