I chose this method because switch .. case is usually well optimized:
#ifdef IS_BIG_ENDIAN
#define CONST16(x) (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8))
#else
#define CONST16(x) (x)
#endif
enum {
CHANGE_LIGHT_INTENSITY = CONST16(0x88AA),
CHANGE_VOLUME = CONST16(0x763D),
};
union {
unsigned char rx_buffer[100];
unsigned short cmd;
} rx;
switch (rx.cmd) {
case CHANGE_LIGHT_INTENSITY:
tx_buffer[0] = 'O';
tx_buffer[1] = 'K';
change_light_intensity(1000);
break;
case CONST16(0x89BB):
tx_buffer[0] = 'O';
tx_buffer[1] = 'K';
tx_buffer[2] = 0x34;
tx_buffer[3] = 0x12;
break;
// many many cases ...
case CHANGE_VOLUME:
tx_buffer[0] = 'O';
tx_buffer[1] = 'K';
change_volume(38);
break;
default:
tx_buffer[0] = 'N';
tx_buffer[1] = 'O';
}
I want to take a closer look at switch ... case construct, because many novice programmers mistakenly believe that it is a replacement for if ... else if ... else construct.
For simplicity, let's look at swith ... case with other, more memorable values:
switch (...) {
case 0: ...; break;
case 5: ...; break;
case 44: ...; break;
case 333: ...; break;
case 2222: ...; break;
case 11111: ...; break;
}
Indeed, without optimization, it's just a regular sequential comparison (gcc 15.2 -O0):
cmp eax, 11111
je .L8 ; == 11111
cmp eax, 11111
jg .L9 ; > 11111
cmp eax, 2222
je .L10 ; == 2222
cmp eax, 2222
jg .L9 ; > 2222
cmp eax, 333
je .L11 ; == 333
cmp eax, 333
jg .L9 ; > 333
cmp eax, 44
je .L12 ; == 44
cmp eax, 44
jg .L9 ; > 44
test eax, eax
je .L13 ; == 0
cmp eax, 5
je .L14 ; == 5
But after optimal compilation, it turns into a binary search, which is embedded in the program code, which means it does not require any additional actions after loading, unlike a manual binary search (gcc 15.2 -O3):
cmp ax, 333
je .L9 ; == 333
ja .L10 ; > 333
cmp ax, 5
je .L11 ; == 5
cmp ax, 44
je .L12 ; == 44
test ax, ax
jne .L14 ; != 0
...
.L10:
cmp ax, 2222
je .L15 ; == 2222
cmp ax, 11111
jne .L14 ; != 11111
The more cases there are, the more the search will approach binary.
tx_buffer[1] = 'O';? you wrotetx_buffer[0] = 'O'.