0

I'm try to write a C application and I use follow code, for read an input parameter of 16 characters

int main(int argc, char *argv[])
{
    unsigned char input[16];

    if (argc != 2) {
        fprintf(stderr,
            "Usage: %s <input> \n",argv[0]);
        return EXIT_FAILURE;
    }

    strncpy((char *)input, argv[1], 16);

    return 0;
 }

Input parameter character is like: "5f52433120d32104" (./myApplication 5f52433120d32104)

I would like get Input characters as byte and put it into an array(5f, 52, 43 etc...), for example:

unsigned char* myByteArray;

Thanks

Livio
  • 205
  • 1
  • 3
  • 9

1 Answers1

0

You can use sscanf to scan your command line parameter in a loop. An example given a variable named inputstr contains your string argument:

char* inputstr = argv[1];
unsigned char myByteArray[ELEMENT_NO]; /*ELEMENT_NO is the number of elements to scan*/
for(int i = 0; i < ELEMENT_NO; ++i)
{
    unsigned int value; /*The value to store the read value in*/
    sscanf(inputstr, "%2x", &value); /*Read 2 hexadecimal digits into value*/
    myByteArray[i] = value; /*Store the new value*/
    inpustr += 2; /*Increase 2 characters*/
}

This way myByteArray will contain your input string read into an array of unsigned char in hexadecimal format.

If you are using a C99 compatible compiler, you can use the "%2hhx" format specifier and read your input into an unsigned char directly, instead of using an intermediate unsigned int.

Shadowwolf
  • 973
  • 5
  • 13