Search code examples
bit-manipulationbitwise-operatorsbit-shiftbitwise-andbitwise-xor

Range checking using bitwise operators in C


I am working on this method, but I am restricted to using ONLY these operators: <<, >>, !, ~, &, ^ and |

I want to do above range checking using bitwise operator, is it possible in a one-line statement?

void OnNotifyCycleStateChanged(int cycleState)
{
   // if cycleState is = 405;
   if(cycleState >= 400 && cycleState <=7936)  // range check 
   {
   // do work ....
   }
} 

Example:

bool b1 = (cycleState & 0b1111100000000); // 0b1111100000000 = 7936

Is this the right way to do that?


Solution

  • bool b1 = CheckCycleStateWithinRange(cycleState, 0b110010000, 0b1111100000000); // Note *: 0b110010000 = 400 and 0b1111100000000 = 7936
    
    bool CheckCycleStateWithinRange(int cycleState, int minRange, int maxRange) const
    {
       return ((IsGreaterThanEqual(cycleState, minRange) && IsLessThanEqual(cycleState, maxRange)) ? true : false );
    }
    
    int IsGreaterThanEqual(int cycleState, int limit) const
    {
       return ((limit + (~cycleState + 1)) >> 31 & 1) | (!(cycleState ^ limit));
    }
    
    int IsLessThanEqual(int cycleState, int limit) const
    {
       return !((limit + (~cycleState + 1)) >> 31 & 1) | (!(cycleState ^ limit));
    }