正在分析C中的十六进制字符串命令



Hi我正试图将一个十六进制命令写入串行端口,在那里我需要将十六进制字符串转换为C中的特定字节数组格式,解析转义符时遇到问题。请帮助实现以下功能。谢谢

int hex2byte(char* write_buf)
{
//code to parse this string into byte array removing escape character and keeping other special character as it is
// resize str, In this case it resize strlen(str)=14 bytes into 5 bytes array; 
// Goal is to Fill the str in this desired way
//   write_buf = {0x02, 0x00, ';' ,';', 0x03};
//      Or
//  write_buf = {0x02, 0x00, 0x3b ,0x3b, 0x03};
return size_of_write_buf;
}

跑步/serial-w"\x02\x00;;\x03">

输出:write_buf=\x02\x00;;\x03尺寸=140x5c、0x78,0x30,0x32,0x5c,0x78,0x30,0x3b、0x3b、0x5c和0x78,0x50,0x33

这里我得到的问题是选项-w write_buf="\x02\x00;;\x03"总共得到14个字节,但我需要这些数据以5个字节为单位,例如0x02、0x00、0x3b、0x3b和0x03。

//serial.c
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <getopt.h>
int  main(int argc, char **argv)
{
int opt;
char *write_buf= NULL;
int i;
while ((opt = getopt(argc, argv, "w:")) != -1)
{
switch (opt) {
case 'w':
write_buf = optarg;
printf("write_buf=%s size=%ld n", write_buf, strlen(write_buf));
for(i=0; i<14; i++)
printf("0x%02xn", write_buf[i]);
/****Implement This function*****/
/*  int size= hex2byte(write_buf);
for (int i=0; i<size;i++)
printf("0x%02xn",write_buf[i]);  
Should print 0x02, 0x00, 0x3b ,0x3b, 0x03.
*/ 
break;
}
}
return 0;
}

您似乎误解了str中的内容。

之后

char* str ="x02x00;;x03";

str指向存储以下值的存储位置:

0x02 0x00 0x3B 0x3B 0x03 0x00
^^^^
Zero termination

正是你所需要的。因此,您不需要函数来转换任何数据。数据已经具有正确的值。

您的问题是找不到大小,因为x00在字符串的中间放置了一个终止符。使用char*无法解决此问题。函数hex2byte(char* str)无法计算出您的示例中有5个字节。

您需要一个固定大小的数组或硬编码大小。但是,如果使用固定大小的数组或硬编码大小,则根本不需要该函数。

请参阅https://ideone.com/bSUeOb对于正在运行的示例

最新更新