C 输入参数的字节转换
我试图编写一个C应用程序,我使用下面的代码来读取16个字符的输入参数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
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*/
}