输入参数的字节转换

Byte conversion for input parameters

我正在尝试编写一个 C 应用程序并使用以下代码读取 16 个字符的输入参数

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

输入参数字符如:"5f52433120d32104" (./myApplication 5f52433120d32104)

我想将输入字符作为字节并将其放入数组(5f、52、43 等...),例如:

unsigned char* myByteArray;

谢谢

您可以使用sscanf循环扫描您的命令行参数。给定名为 inputstr 的变量的示例包含您的字符串参数:

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*/
}

这样 myByteArray 将包含以十六进制格式读入 unsigned char 数组的输入字符串。

如果您使用的是 C99 兼容编译器,则可以使用 "%2hhx" 格式说明符并将输入直接读入 unsigned char,而不是使用中间 unsigned int