Sscanf 1 byte data without overflow

I need to scan a 6 byte hexadecimal data representation and store it in a 6 byte array.

Please note, I am on an embedded system, so each byte counts.

Using sscanf like this:

uint8_t buf[6];
char hex[13] = "123456789ABC";
sscanf(hex, "%02X%02X%02X%02X%02X%02X", &buf[0], &buf[1], &buf[2], &buf[3], &buf[4], &buf[5]);

      

overflows because each% 02X specifier is loaded into uint32_t.

  • % 02lX will be loaded into uint32_t
  • % 02hX will be loaded into uint16_t

Is there a specifier that gets loaded into uint8_t? (I don't find anything)

Is there any other way to do this?

I tried to do:

sscanf(hex, "%08lX%04hX", &buf[0], &buf[4]);

      

it does not overflow, but since I am in a small structure the order is mixed ...

+3


source to share


2 answers


You want to use% 02hhX on unsigned char array. (So ​​uint8_t is great)



+6


source


Please note, I am on an embedded system, so each byte counts.

If so, then sscanf is probably not recommended; its stack usage and code space will overshadow any savings you might perceive when using the smallest data type possible. 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 will look like this:



char hex[13] = "123456789ABC";

for( int b = 0; b < 6; b++ )
{
    buf[b] = hexbyte( &hex[b * 1] ) ;
}

      

If you must use sscanf()

, but your library does not support a format specifier hh

(as many built-in or older C libraries cannot), you can use an intermediate integer:

char hex[13] = "123456789ABC";

for( int b = 0; b < 6; b++ )
{
    unsigned byte ;

    buf[b] = hexbyte( &hex[b * 1] ) ;
    sscanf( &hex[b * 2], "%02X", byte ) ;
    buf[b] = (unit8_t)byte ;
}

      

+5


source







All Articles