static std::string ByteLenStr(std::string& sHexStr)
{
int iLen = ByteLen(sHexStr);
char buffer[16];
snprintf(buffer, sizeof(buffer), (iLen > 255) ? "%04x" : "%02x", iLen);
return buffer;
}
snprintf formats text in a buffer using a format string and a variable list of arguments. We are using the %x format code to convert a int
argument into a hex string. In this instance, we have two format strings to choose from:
- When
iLen > 255
, we want the number to be four digits long. %04x means format as a hex string, with zero-padding at the beginning up to four places. - Otherwise, we want the number to be two digits long. %02x means format as a hex string, with zero-padding up to two places.
We use the ternary operator to select which format string we use. Finally, iLen
is passed as the single argument which will be used to provide the value that is formatted by the function.