Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/rest/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 输入参数的字节转换_C_Byte - Fatal编程技术网

C 输入参数的字节转换

C 输入参数的字节转换,c,byte,C,Byte,我试图编写一个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

我试图编写一个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;
 }

谢谢

您可以使用
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*/
}
char*inputstr=argv[1];
无符号字符myByteArray[元素号]/*ELEMENT_NO是要扫描的元素数*/
对于(int i=0;i
这样,
myByteArray
将包含输入字符串,该字符串以十六进制格式读入
无符号字符的数组


如果您使用的是C99兼容的编译器,您可以使用
%2hhx”
格式说明符,直接将输入读入
无符号字符
,而不是使用中间的
无符号整数

是否需要将其转换为六进制数?这就是您要寻找的吗?
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*/
}