In my program, I have an enum that is used for indexing my array members. The reason is that it is much easier for me to understand which parameter I am accessing without knowing its index in the array
enum param_enum
{
AA,
AB,
AC,
AD,
PARAM_COUNT
};
static int16_t parameters[PARAM_COUNT] =
{
[AA] = 5,
[AB] = 3,
[AC] = 4,
[AD] = 8,
};
I can then access any parameter for example:
parameters[AA] = 10; // Update AA parameter to value 10.
I will be receiving serial commands such as :
"AA:15"
When I receive this command, I must determine what parameter I need to modify based on the first 2 characters, then skip the 3rd character( because it is just ":" and I dont care about it) and the remaining characters will show the new value)
I wonder if there is any easier way to map the enum to a string
My current method:
// 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;
}
}
The above method seems to work fine but I do not believe that this is the most appropriate solution for this particular task.
CodePudding user response:
If you don't mind what the actual values of the enumeration constants are, you could define those values to be equivalent to the first two characters of the test string. You can then copy those first two characters into a variable of that enum
type, which will then adopt the appropriate enumeration directly.
You can define the values using two-character integer literals (like 'BA'
). On little-endian systems (such as Windows), the two characters would be in reverse order; for big-endian systems, they would be in direct order.
Here's an example little-endian implementation:
#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("