1

I am only learning C and I am trying to loop though an array of strings and then convert to a byte array using sscanf.

#define BYTE   unsigned char

char stringarray[][3]
{
    "98D9C2327F1BF03",
    "98D9EC2327F1BF03",
    "98D9EC2327F1BF03",
}

int main()
{   
    size_t i = 0;
    for (i = 0; i < sizeof(stringarray) / sizeof(stringarray[0]); i++)
    {
        char hexstring[] = stringarray[i], *position[] = hexstring;
        BYTE HexByteArray[8];
        size_t count= 0;

        for (count = 0; count < sizeof(HexByteArray) / sizeof(HexByteArray[0]); count++) {
        sscanf(position, "%2hhx", &HexByteArray[count]);
        position += 2;

        }       
    }

     return 0;
}

Error using visual studio 2013

initializing' : cannot convert from 'char [3]' to 'char []
initialization with '{...}' expected for aggregate object
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Jimbo Jones
  • 983
  • 4
  • 13
  • 48

1 Answers1

1

Untested (but it's based on this), but it should be enough to get you started:

#include <stdio.h>    // sscanf
#include <string.h>   // strcpy

#define BYTE   unsigned char

// you want 3 strings of a length at least 17 (+1 for null terminator)
char stringarray[3][17]
{
    "98D9C2327F1BF03",
    "98D9EC2327F1BF03",
    "98D9EC2327F1BF03",
};

int main()
{
    size_t i = 0;
    for (i = 0; i < sizeof(stringarray) / sizeof(stringarray[0]); i++)
    {
        char hexstring[17];
        // copy stringarray[i] to hexstring
        strcpy(hexstring, stringarray[i]);
        // use a pointer
        char *position = hexstring;
        BYTE HexByteArray[8];
        size_t count= 0;

        for (count = 0; count < sizeof(HexByteArray) / sizeof(HexByteArray[0]); count++) {
            sscanf(position, "%2hhx", &HexByteArray[count]);
            position += 2;
        }
        printf("%u\n", HexByteArray[0]);
    }
    return 0;
}

is what you want to use when dealing with strings in , check it out! ;)

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305