Reputation: 43
/* UART HEADER */
#define featureA 0xA0
#define featureB 0xB0
#define featureC 0x20
-
-
-
- // increment on feature, value of feature are random
-
-
#define featureZ 0x??
#define CHECK_CHAR(x) ((x==featureA)||(x==featureB)||(x==featureC) ------- (x==featureZ)? TRUE: FALSE)
Hi all, I got a set of UART header that to indicate what the commands for. So every time I am checking the header using the macro, but I realize that when the command is keep increasing and the macro length also keep increasing, it make the code very messy. I am looking for a mechanism to handle this checking when the feature is more and more.
Upvotes: 0
Views: 92
Reputation: 213711
Since this seems to be a run-time check, you can speed up the program considerably by using a look-up table instead. It will also make the code more readable. Assuming you can spare 256 bytes of flash and all codes are unique, then:
bool CHECK_CHAR (uint8_t ch)
{
const bool LOOKUP [256] =
{
[featureA] = true,
[featureB] = true,
[featureC] = true,
};
return LOOKUP[ch];
}
The second best option is a sorted array of uint8_t
constants + binary search.
Upvotes: 1
Reputation: 6740
Assuming that your values follow the simple pattern above, this would work:
#define CHECK_CHAR(x) ( ((x)&0xf) == 0 && (x) >= featureA && (x) < featureInvalid )
where you define featureInvalid
to be the next logical value after featureZ
.
Upvotes: 0