C++ 参考手册

定义于头文件 <bit>
template<class T>
[[nodiscard]] constexpr T rotr(T x, int s) noexcept;
(C++20 èµ·)

计算将 x 右旋转 s 位的结果。此运算被称为循环移位。

正式而言,令 N 为 std::numeric_limits<T>::digits , r 为 s % N 。

  • è‹¥ r 为 0 ,则返回 x ï¼›
  • è‹¥ r 为正,则返回 (x >> r) | (x << (N - r)) ï¼›
  • è‹¥ r 为负,则返回 std::rotl(x, -r) 。

此重载仅若 T 为无符号整数类型(即 unsigned char 、 unsigned short 、 unsigned int 、 unsigned long 、 unsigned long long 或扩展无符号整数类型)才参与重载决议。

参数

x - 无符号整数类型的值

返回值

将 x 右旋转 s 位的结果。

示例

#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
 
int main()
{
    std::uint8_t i = 0b00011101;
    std::cout << "i          = " << std::bitset<8>(i) << '\n';
    std::cout << "rotr(i,0)  = " << std::bitset<8>(std::rotr(i,0)) << '\n';
    std::cout << "rotr(i,1)  = " << std::bitset<8>(std::rotr(i,1)) << '\n';
    std::cout << "rotr(i,9)  = " << std::bitset<8>(std::rotr(i,9)) << '\n';
    std::cout << "rotr(i,-1) = " << std::bitset<8>(std::rotr(i,-1)) << '\n';
}

输出:

i          = 00011101
rotr(i,0)  = 00011101
rotr(i,1)  = 10001110
rotr(i,9)  = 10001110
rotr(i,-1) = 00111010

参阅

(C++20)
计算逐位左旋转的结果
(函数模板)