【问题标题】:Parsing hex string command in C在 C 中解析十六进制字符串命令
【发布时间】: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


【解决方案1】:

您似乎误解了 str 开头的内容。

之后

char* str ="\x02\x00;;\x03";

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

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

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

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

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

查看https://ideone.com/bSUeOb 了解运行示例

【讨论】:

    猜你喜欢
    • 2019-08-03
    • 2015-11-19
    • 1970-01-01
    • 2015-08-02
    • 2016-07-17
    • 2011-04-08
    • 1970-01-01
    • 2010-12-30
    • 2016-12-15
    相关资源
    最近更新 更多