【问题标题】:Range checking using bitwise operators in C在 C 中使用位运算符进行范围检查
【发布时间】:2018-05-15 05:14:27
【问题描述】:

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

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

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

例子:

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

这是正确的方法吗?

【问题讨论】:

  • 代码没有意义。它说它检查 405,然后将 400 分配给变量而不是进行比较。如果是 400 或 405,肯定小于 7936,所以不需要第二次比较。您能否再澄清一下这个问题?
  • 您的if() 有一个任务。这是故意的吗?即使是相等比较,它也永远不会有意义,因为 400 的 cycleState 已经小于 7936。
  • 我写错了
  • 检查我更新代码。

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


【解决方案1】:
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));
}

【讨论】:

    猜你喜欢
    • 2011-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-10
    • 2015-01-14
    相关资源
    最近更新 更多