循环一个字符串数组,然后使用sscanf_s c转换为一个字节

时间:2016-12-09 10:35:14

标签: c arrays string loops for-loop

我只是在学习C,我试图循环一个字符串数组,然后使用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;
}

使用visual studio 2013时出错

initializing' : cannot convert from 'char [3]' to 'char []
initialization with '{...}' expected for aggregate object

1 个答案:

答案 0 :(得分:1)

未经测试(但它基于this),但它应该足以让您入门:

#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;
}

是您在处理中的字符串时要使用的内容,请查看! ;)