在我的程序中,我有一个枚举用于索引我的数组成员。原因是,在不知道数组中索引的情况下,我更容易理解正在访问哪个参数
enum param_enum
{
AA,
AB,
AC,
AD,
PARAM_COUNT
};
static int16_t parameters[PARAM_COUNT] =
{
[AA] = 5,
[AB] = 3,
[AC] = 4,
[AD] = 8,
};
然后我可以访问任何参数,例如:
parameters[AA] = 10; // Update AA parameter to value 10.
我将接收串行命令,例如:
"AA:15"
当我收到这个命令时,我必须根据前2个字符确定需要修改哪些参数,然后跳过第3个字符(因为它只是“:”,我不关心它),其余字符将显示新值)
我想知道是否有更简单的方法将枚举映射到字符串
我当前的方法:
// line holds the string data
// cmd_size is the length of string data
bool parse_command(char *line, uint16_t cmd_size)
{
printf("data size = %u \n",cmd_size);
char temp_buf[3] = {0};
temp_buf[0] = line[0];
temp_buf[1] = line[1];
printf("temp_buf = %s \n",temp_buf);
if (!strcmp("aa", temp_buf))
{
printf("aa: detected \n");
char temp_storage[5];
int16_t final_value;
for(int i = 3;i<=cmd_size; i++){
temp_storage[i-3]=line[i]; // read data and append to temp bufferfrom the 3rd character till the end of line
if(line[i] == 0){
printf("null termination triggered \n");
final_value = strtol(temp_storage,NULL,10); // convert char array to int16_t
printf("temp var = %i \n",final_value);
}
}
return true;
}
}
上述方法似乎工作正常,但我不认为这是针对此特定任务的最合适的解决方案。
最佳答案
如果您不介意枚举常量的实际值是什么,您可以将这些值定义为等于测试字符串的前两个字符。然后,您可以将前两个字符复制到该枚举类型的变量中,该变量将直接采用适当的枚举。
您可以使用两个字符的整数文字(例如'BA'
)来定义值。在小端系统(例如 Windows)上,两个字符的顺序相反;对于大端系统,它们将按直接顺序排列。
这是一个小端实现示例:
#include <stdio.h>
#include <string.h>
enum param_enum {
// Reverse byte order from strings for little-endian; keep "as-is" for big-endian...
AA = 'AA',
AB = 'BA',
AC = 'CA',
AD = 'DA'
};
int main(void)
{
char test[100];
while (1) {
printf("Enter test string (Q to quit): ");
if (scanf("%99s", test) != 1 || strcmp(test, "Q") == 0) break;
enum param_enum penum;
memset(&penum, 0, sizeof(penum)); // To clear any 'upper' bytes
memcpy(&penum, test, 2); // Now copy the first 2 byte2
switch (penum) {
case AA:
printf("Code is AA.\n");
break;
case AB:
printf("Code is AB.\n");
break;
case AC:
printf("Code is AC.\n");
break;
case AD:
printf("Code is AD.\n");
break;
default:
printf("Unknown code.\n");
break;
}
}
return 0;
}
如果您的编译器不支持多字 rune 字(根据 C 标准,IIRC,这种支持是可选的),您可以使用十六进制常量和字符的 ASCII 代码指定等效值(假设您的平台使用 ASCII 编码),相反:
enum param_enum {
AA = 0x4141, // 'AA'
AB = 0x4241, // 'BA'
AC = 0x4341, // 'CA'
AD = 0x4441 // 'DA'
};
关于c - 将字符串映射到枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69176354/