yath
yath

Reputation: 355

Reading Hex from command line to unsigned char and unsigned short

int main(int argc, char *argv[]){
    unsigned char Data = 0xff;
    unsigned short addr = 0xff;

    sscanf(argv[1], "%u", &Data);
    sscanf(argv[2], "%hu", &addr);

    printf("data is %u addr is %hu ", Data, addr);

    return 0;
}

Hi, I am trying to read command line arguments of hex format into unsigned char and unsigned short. Please check the above code snippet. The output is always 0xff (initialized value). May I know what needs to be changed to read the inputs?

Upvotes: 0

Views: 1144

Answers (2)

4386427
4386427

Reputation: 44274

By using the %u specifier you tell sscanf that you want to read an an unsigned int in decimal format (base 10). If you want hex input (base 16) you must use the %x specifier. Further you need to specify the correct integer size. For unsigned char you will need hh as length modifier. Using the wrong length modifier is a cause of undefined behaviour.

So you should try the %hhx specifier. Something like:

#include <stdio.h>

int main(void){
    unsigned char Data = 0xff;

    char argv1[20] = "0x40";

    sscanf(argv1, "0x%hhx", &Data);

    printf("data is %u\n", Data);

    return 0;

}

Output: data is 64

For unsigned short in hex you should use %hx

Upvotes: 3

David Ranieri
David Ranieri

Reputation: 41017

The unsigned char specificier for C99 and later is %hhx

Upvotes: 2

Related Questions