Search code examples
c#optimizationrangecomparison

Optimize multiple comparison conditions


My main code needs to compare an integer ASCII command and I wonder if there is a solution to optimize this.

I can send from '1' to '128' on the serial bus, and to reach the proper object, here is how I do:

// this is how I deal with the data sent on the serial bus 
int translateASCII(char requestBuffer[10]){
    char word[4] = {0};
    word[0] = (int)requestBuffer[0];
    word[1] = (int)requestBuffer[1];
    word[2] = (int)requestBuffer[2];
    int n = atoi(word);
    return n;
}

void interpreteASCII(int ascii){
    if (ascii > 0 && ascii < 33){
        if (ascii < 9){
            blabla
        }
        else if (ascii < 17){
            blabla
        }
        else if (ascii < 25){
            blabla
        }
        else
            blabla
    }
    else if (ascii < 65){
        if (ascii < 41){
            blabla
        }
        else if { ... }
    }            
}

So I'm looking for a way to optimize this 'architecture'. Also thought about a switch case function but it seems to only compare my ASCII variable to a single integer like:

switch (ascii){
     case '8':
         blabla

and this is not what I'm looking for because the instructions really depend on the ASCII variable which is sorted by intervals of 32 ​​which themselves must be sorted by intervals of 8 values.


Solution

  • You say you need one case for each interval of 8, e.g. 1-8, 9-16 etc. Try this:

    switch ((ascii + 7)/ 8) {
    case 0: // input was zero
        break;
    case 1: // input was in [1..8]
        break;
    // ...
    case 8: // input was in [57..64]
        break;
    }