Search code examples
cprintfhextype-conversionbitconverter

sprintf not giving expected values


I have an array (readingreg[4]) that gets filled with hex digits. My goal is to convert the datatype into a string. I have read some suggestions and it seems that sprintf is the way to go.

This is what I tried:

sprintf(server0, "0x%02X", readingreg[0]);
printf("This is element 0: %s\n", server0);

sprintf(server1, "0x%02X", readingreg[1]);
printf("This is element 1: %s\n", server1);

sprintf(server2, "0x%02X", readingreg[2]);
printf("This is element 2: %s\n", server2);

sprintf(server3, "0x%02X", readingreg[3]);
printf("This is element 3: %s\n", server3);


printf("This is element 0: %s\n", server0);
printf("This is element 1: %s\n", server1);
printf("This is element 2: %s\n", server2);
printf("This is element 3: %s\n", server3);

Here is my output:

This is element 0: 0x4A
This is element 1: 0xAA
This is element 2: 0xAA
This is element 3: 0xA0
This is element 0: 0
This is element 1: A0
This is element 2: xA0
This is element 3: 0xA0

At this point, I am pretty confused on what sprintf has done for me. My expected output is that server0 - server4 all retain their string values. Any idea to why this is occurring?

Here is a simplified version of the program:

readingreg[0] = 4A;
readingreg[1] = AA;
readingreg[2] = AA;
readingreg[3] = A0;
char server0[1];
char server1[1];
char server2[1];
char server3[1];

The full program is over 1000 lines of code so what I provided should be sufficient enough to compile and run.


Solution

  • When you do:

    char server0[1];
    sprintf(server0, "0x%02X", readingreg[0]);
    

    you are trying to put 5 characters (don't forget the trailing '\0') into a 1 character buffer. This results in undefined behaviour which happens to show itself in the observed output.

    What you should do (at least) is make the character buffer large enough to store whatever you are putting in it:

    char server0[8];
    sprintf(server0, "0x%02X", readingreg[0]);
    

    A better solution would be to make the array larger and use snprintf() or a similar function to ensure you don't overflow the character buffer:

    char server0[8];
    snprintf (server0, sizeof(server0)/sizeof(server0[0]), "0x%02X", readingreg[0]);