I have an input like
char *input="00112233FFAA";
uint8_t output[6];
What is the easiest way to convert input into output with sscanf? (prefer 1 line with no loop) The solution I have in mind doesn't scale to 20+ hex string.
sscanf(input, "%x%x%x%x%x",output[0], output[1]....output[5]);
解决方案
Why scanf if this can be easily written by hand:
const size_t numdigits = strlen(input) / 2;
uint8_t * const output = malloc(numdigits);
for (size_t i = 0; i != numdigits; ++i)
{
output[i] = 16 * toInt(input[2*i]) + toInt(intput[2*i+1]);
}
unsigned int toInt(char c)
{
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'A' && c <= 'F') return 10 + c - 'A';
if (c >= 'a' && c <= 'f') return 10 + c - 'a';
return -1;
}