如何仅使用 + - & | 向右移动并测试 >、< ==

问题描述 投票:0回答:1

之前询问过,但由于缺乏细节而被关闭。所以这里有更多信息

我正在 cp 上工作,没有移位或旋转。

支持

  • 加减法
  • 逻辑与和逻辑或
  • 条件跳转 > < == or any combination of those (>=...)

我可以看到如何使用重复添加到自身来向左移动。我可以通过在移位前测试最左边的位并在移位后将其或到最右边来进行旋转。

但我想不出右移机制

bit-manipulation
1个回答
0
投票

这是使用

+
-
&
的 C++ 示例:

#include <numeric>

template<class T>
T rightshift(T value, int steps) {
    T div = 1;
    while(steps--) div += div; // steps=1 => 2, 2 => 4 etc.

    // zero out the bits that will be shifted out so that
    // value will be evenly divisible by div:
    T mask = std::numeric_limits<T>::max() - (div - 1);
    value &= mask;
    
    T res = 0;
    while(value) { // subtract div until value reaches zero
        value -= div;
        ++res;     // and count the number of times we subtract
    }

    return res;
}
© www.soinside.com 2019 - 2024. All rights reserved.