0

我正在研究这种方法,但我仅限于使用这些运算符:<<, >>, !, ~, &,^|

我想使用按位运算符进行上述范围检查,是否可以在一行语句中进行?

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

例子:

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

这是正确的方法吗?

4

1 回答 1

0
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));
}
于 2018-05-17T11:07:11.890 回答