c++ - 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;
这里有什么不同?
解决方案
[expr.shift]/1
7.6.7 移位运算符
移位运算符 << 和 >> 从左到右分组。
移位表达式:
加法表达式
移位表达式 << 加法表达式
移位表达式>>加法表达式
操作数应为整数或非范围枚举类型,并执行整数提升。结果的类型是提升的左操作数的类型。如果右操作数为负数,或者大于或等于提升的左操作数的位长度,则行为未定义。
推荐阅读
- ios - Swift UIPageViewController - 用于请求的脊椎位置 (UIPageViewControllerSpineLocationMin)
- java - 无法使用 elasticsearch-keystore 命令读取值
- java - 我如何捕获请求标头中动态变化的引用值
- node.js - WAV 标头指示不支持的格式。在谷歌云语音到文本 API
- ios - 添加新数据时可编码和 firebase 警告会导致错误。任何解决方法?
- image - 我想将资产文件夹中的自定义页脚图像放置到我的应用程序屏幕底部的颤振应用程序中
- c - PAM 在 C 中对用户进行身份验证
- java - 以编程方式将库添加到引用的库
- ios - NSNotificationCenter 语法
- reactjs - 开始学习反应,我正在尝试使用 unsplash API 构建一个简单的图像搜索,但我无法渲染到页面