【问题标题】:Bithacking comparison (less) operatorBithacking 比较(更少)运算符
【发布时间】:2015-11-18 12:38:35
【问题描述】:

我知道大多数算术运算只能使用按位运算符(Add two integers using only bitwise operators?Multiplication of two integers using bitwise operators 等...)来完成。

我也知道,如果你有 less 运算符,你可以从中推断出其他运算符 (Sorting only using the less-than operator compared to a trivalue compare function)

所以...如果有一种方法可以仅使用按位运算来实现 less 运算符,我只是好奇。

喜欢:

bool less(int a, int b) { ??? }

为了让它更复杂:

template<typename T> bool less(T a, T b) { ??? }

其中 T 肯定是整数型数字类型(8 ... 64 位)

【问题讨论】:

    标签: c++ bit-manipulation bitwise-operators bit


    【解决方案1】:

    当然可以。假设补码:

    bool less(int a, int b)
    {
      const unsigned int bits = sizeof(int) * CHAR_BIT;
      const unsigned int sign_bit = 1u << (bits - 1);
      unsigned int lhs = a;
      unsigned int rhs = b;
      bool negative = (lhs & sign_bit);
      if (negative && !(rhs & sign_bit))
        return negative;
      for (unsigned int bit == 1u << (bits - 2); bit != 0u; bit >>= 1) {
        if ((lhs & bit) != (rhs & bit)) {
          return !(lhs & bit);
        }
      }
    }
    

    在适当的make_unsigned&lt;T&gt; trait 的帮助下,模板版本可以同样工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 2021-01-13
      • 2019-08-13
      • 1970-01-01
      相关资源
      最近更新 更多