首页 > 解决方案 > C ++避免位操作中的完全移位

问题描述

template<class _Diff,
        class _Urng>
        class _Rng_from_urng
    {   // wrap a URNG as an RNG
    public:
        explicit _Rng_from_urng(_Urng& _Func)
            : _Ref(_Func), _Bits(CHAR_BIT * sizeof(_Udiff)), _Bmask(_Udiff(-1))
        {   // construct from URNG
            for (; (_Urng::max)() - (_Urng::min)() < _Bmask; _Bmask >>= 1)
                --_Bits;
        }

        _Diff operator()(_Diff _Index)
        {   // adapt _Urng closed range to [0, _Index)
            for (;;)
            {   // try a sample random value
                _Udiff _Ret = 0;    // random bits
                _Udiff _Mask = 0;   // 2^N - 1, _Ret is within [0, _Mask]

                while (_Mask < _Udiff(_Index - 1))
                {   // need more random bits
                    _Ret <<= _Bits - 1; // avoid full shift
                    _Ret <<= 1;
                    _Ret |= _Get_bits();
                    _Mask <<= _Bits - 1;    // avoid full shift
                    _Mask <<= 1;
                    _Mask |= _Bmask;
                }

                // _Ret is [0, _Mask], _Index - 1 <= _Mask, return if unbiased
                if (_Ret / _Index < _Mask / _Index
                    || _Mask % _Index == _Udiff(_Index - 1))
                    return (_Ret % _Index);
            }
        }
    };
}

上面的代码是从stl粘贴过来的。“避免全班”是什么意思?我认为两个位移位可以集成到单个操作中。

_Ret <<= _Bits - 1; // avoid full shift 
_Ret <<= 1;

我将代码更改为:

_Ret<<=_Bits;

这里有什么不同?

标签: c++bit

解决方案


[expr.shift]/1

7.6.7 移位运算符

  1. 移位运算符 << 和 >> 从左到右分组。

    移位表达式:

    加法表达式

    移位表达式 << 加法表达式

    移位表达式>>加法表达式

    操作数应为整数或非范围枚举类型,并执行整数提升。结果的类型是提升的左操作数的类型。如果右操作数为负数,或者大于或等于提升的左操作数的位长度,则行为未定义


推荐阅读