scanf("%d", char*) - char-as-int format string?

11,316

Solution 1

You can use %hhd under glibc's scanf(), MSVC does not appear to support integer storage into a char directly (see MSDN scanf Width Specification for more information on the supported conversions)

Solution 2

It is dangerous to use that. Since there an implicit cast from a unsigned char* to an int*, if the number is more than 0xFF it is going to use bytes (max 3) next to the variable in the stack and corrupt their values.

The issue with %hhd is that depending of the size of an int (not necessarily 4 bytes), it might not be 1 byte.

It does not seem sscanf support storage of numbers into a char, I suggest you use an int instead. Although if you want to have the char roll-over, you can just cast the int into a char afterward, like:

int dest;
int len;

len = sscanf(source,"%c%d",&separator,&dest);
dest = (unsigned char)dest;
Share:
11,316
SF.
Author by

SF.

1HX7uW46E23S2fMdWXzddjGCDFT8T9Boh8

Updated on June 04, 2022

Comments

  • SF.
    SF. almost 2 years

    What is the format string modifier for char-as-number?

    I want to read in a number never exceeding 255 (actually much less) into an unsigned char type variable using sscanf.

    Using the typical

     char source[] = "x32";
     char separator;
     unsigned char dest;
     int len;
    
     len = sscanf(source,"%c%d",&separator,&dest);
     // validate and proceed...
    

    I'm getting the expected warning: argument 4 of sscanf is type char*, int* expected.

    As I understand the specs, there is no modifier for char (like %sd for short, or %lld for 64-bit long)

    • is it dangerous? (will overflow just overflow (roll-over) the variable or will it write outside the allocated space?)
    • is there a prettier way to achieve that than allocating a temporary int variable?
    • ...or would you suggest an entirely different approach altogether?