【发布时间】:2020-03-11 11:32:01
【问题描述】:
您好我正在尝试将十六进制命令写入串行端口,我需要将十六进制字符串转换为 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 大小=14 0x5c,0x78,0x30,0x32,0x5c,0x78,0x30,0x30,0x3b,0x3b,0x5c,0x78,0x30,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%02x\n", write_buf[i]);
/****Implement This function*****/
/* int size= hex2byte(write_buf);
for (int i=0; i<size;i++)
printf("0x%02x\n",write_buf[i]);
Should print 0x02, 0x00, 0x3b ,0x3b, 0x03.
*/
break;
}
}
return 0;
}
【问题讨论】:
-
那个函数没有任何意义......实际代码在哪里?
-
嗯...函数返回
char*但返回值保存在一个int... -
“期望的输出:0x02 0x00 0x3b 0x3b 0x03”是什么意思。只需打印 ASCII 值而不解析任何内容?
-
进一步,
return size_of_array建议返回与返回类型char*再次冲突的整数类型 -
而且...数组已经包含这些值
标签: c