gpt4 book ai didi

c - 解析具有各种字段的消息,然后根据字段运行命令的最佳方法是什么?

转载 作者:太空宇宙 更新时间:2023-11-04 03:30:10 26 4
gpt4 key购买 nike

所以现在我定义了一个如下所示的结构:

typedef struct rec_msg {
uint8_t unit[4];
uint8_t subdevice[4];
uint8_t command[4];
uint16_t data[3];
uint16_t msg_id[1];
} rec_msg;

...我想读取结构中的字符数组,然后基于它们运行命令。现在我正在这样做,而且似乎会有一种更简洁的方法来做到这一点。

 if (strncmp((const char *)message->unit, "blah", 3) == 0)
{
if (strncmp((const char *)message->subdevice, "syr", 3) == 0)
{
if (strncmp((const char *)message->command, "rem", 3) == 0)
{
// run some command
}
else if (strncmp((const char *)message->command, "dis", 3) == 0)
{
// run some command
}
else
{
DEBUG_PRINT("Message contains an improper command name");
}
}
else if (strncmp((const char *)message->subdevice, "rot", 3) == 0)
{
if (strncmp((const char *)message->command, "rem", 3) == 0)
{
// run some command
}
else if (strncmp((const char *)message->command, "dis", 3) == 0)
{
// run some command
}
else
{
DEBUG_PRINT("Message contains an improper command name");
}
}
else
{
DEBUG_PRINT("Message contains an improper subdevice name");
}
}
else
{
DEBUG_PRINT("Message contains the wrong unit name");
}
}

最佳答案

不是针对一般问题的明确代码,而是将任务分解为多个步骤。伪代码如下。

对于 3 组字符串中的每一组,将匹配的文本转换为数字。建议具有相应枚举的字符串数组。 (如下图2)

enum unit_index {
unit_blah,
unit_N
};

const char *unit_string[unit_N] = {
"blah"
};

enum subdevice_index {
subdevice_syr,
subdevice_rot,
subdevice_N
};

const char *subdevice_string[subdevice_N] = {
"syr"
"rot"
};

查找匹配索引

unit_index unit = find_index(message->unit, unit_string, unit_N);
if (unit >= unit_N) {
DEBUG_PRINT("Message contains the wrong unit name");
return FAIL;
}

subdevice_index subdevice = find_index(message->subdevice, subdevice_string, subdevice_N);
if (subdevice >= subdevice_N) {
DEBUG_PRINT("Message contains the wrong subdevice name");
return FAIL;
}

// similar for command

现在代码有 3 个索引对应于 3 个文本字段。

创建索引表及相应命令

typedef struct {
enum unit_index unit;
enum subdevice_index subdevice;
enum command_index command;
int (*func)();
} index2func;

index2func[] = {
{ unit_blah, subdevice_syr, command_dis, command_blah_syr_dis },
{ unit_blah, subdevice_rot, command_dis, command_blah_rot_dis },
...
{ unit_blah, subdevice_rpt, command_rem, command_blah_rot_rem }
};

遍历表以获得一组匹配的索引并执行命令。

关于c - 解析具有各种字段的消息,然后根据字段运行命令的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37467361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com