sscanf 1 byte hex data without overflow
Please note I am in an embedded system so every byte count.
If that is the case then sscanf is probably ill-advised; its stack usage and code space will dwarf any saving you might perceive in using the smallest possible data type. Consider:
uint8_t hexdigit( char hex )
{
return (hex <= '9') ? hex - '0' :
toupper(hex) - 'A' + 10 ;
}
uint8_t hexbyte( const char* hex )
{
return (hexdigit(*hex) << 4) | hexdigit(*(hex+1)) ;
}
Then your code becomes:
char hex[13] = "123456789ABC";
for( int b = 0; b < 6; b++ )
{
buf[b] = hexbyte( &hex[b * 2] ) ;
}
If you must use sscanf()
but your library does not support the hh
format specifier qualifier (as many embedded or older C libraries may not), then you can use an intermediate integer:
char hex[13] = "123456789ABC";
for( int b = 0; b < 6; b++ )
{
unsigned byte ;
sscanf( &hex[b * 2], "%02X", byte ) ;
buf[b] = (unit8_t)byte ;
}
You want to use %02hhX
on an array of unsigned char. (So uint8_t
is fine)