简体   繁体   中英

s(n)printf prints more characters than format specifier specifies

I am encountering a curious issue with sprintf on an embedded system (Libelium Waspmote, similar to Arduino) where sprintf is outputting more characters than given by the format specifier. In this particular instance I am using %02X to output the hexadecimal value of bytes in an array. However on some bytes, instead of writing 2 characters, 4 are being written, with FF being prefixed before the actual byte value. snprintf behaves similarly, except that it respects the buffer size specified and just prints the prefix.

For reference, here is the code snippet printing the array contents:

char *pduChars = (char *) malloc(17*sizeof(char));
pduData.toChar(pduChars);
for (int i = 0; i < 17; i++) {
    char asciiCharsS[5];
    char asciiCharsSN[3];
    int printedS = sprintf(asciiCharsS, "%02X", pduChars[i]);
    int printedSN = snprintf(asciiCharsSN, 3, "%02X", pduChars[i]);
    USB.print(printedS);
    USB.print(" ");
    USB.print(printedSN);
    USB.print(" ");
    USB.print(asciiCharsS);
    USB.print(" ");
    USB.print(asciiCharsSN);
    USB.println(" ");
}

And the output from that snippet (abridged to only the erroneous bytes): The actual byte sequence should be 0x00 0xFC 0xFF 0xFF 0x48 0xA5 0x33 0x51

sprintf snprintf sprintf Buffer snprintf Buffer


2 2 00 00
4 4 FFFC FF
4 4 FFFF FF
4 4 FFFF FF
2 2 48 48
4 4 FFA5 FF
2 2 33 33
2 2 51 51

Am I overlooking something here or might this be a platform-specific issue relating to the implementation of s(n)printf ?

I'm guessing your implementation is using signed chars. The format "%X" expects unsigned values. Cast or use unsigned char instead.

/* cast */
int printedS = sprintf(asciiCharsS, "%02X", (unsigned char)pduChars[i]);
int printedSN = snprintf(asciiCharsSN, 3, "%02X", (unsigned char)pduChars[i]);

or

/* use unsigned char */
unsigned char *pduChars = malloc(17); /* cast is, at best, redundant */
                                      /* sizeof (char) is, by definition, 1 */

The format specifier modifiers you are using are only used for padding. In case the value's number of symbols exceeds the specified value, the whole string will be printed.

%02X用于填充...不会省略...因此,如果您的值大于指定的值,则将打印整个字符串

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM