使用C中的按位运算符进行范围检查

时间:2018-05-15 05:14:27

标签: bit-manipulation bitwise-operators bit-shift bitwise-and bitwise-xor

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

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

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

示例:

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

这是正确的方法吗?

1 个答案:

答案 0 :(得分: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));
}
相关问题