Namespaces
Variants

std::rotr

来自 zh.cppreference.net
 
 
 
位操作
(C++20)
(C++23)
2 的整数次幂 2
(C++20)
(C++20)
(C++20)
移位
(C++29)
(C++29)
旋转
(C++20)
(C++20)
计数
(C++20)
(C++20)
(C++20)
置换
(C++29)
(C++29)
字节序
(C++20)
 
定义于头文件 <bit>
template< class T >
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 - 无符号整型数值
s - 位移位数

返回值

将 x 按位右旋转 s 个位置的结果。

注释

功能测试 宏 值 标准 功能
__cpp_lib_bitops 201907L (C++20) 位操作

示例

#include <bit>
#include <bitset>
#include <cstdint>
#include <iostream>
int main()
{
    using bin = std::bitset<8>;
    const std::uint8_t x{0b00011101};
    std::cout << bin(x) << " <- x\n";
    for (const int s : {0, 1, 9, -1, 2})
        std::cout << bin(std::rotr(x, s)) << " <- rotr(x, " << s << ")\n";
}

输出:

00011101 <- x
00011101 <- rotr(x, 0)
10001110 <- rotr(x, 1)
10001110 <- rotr(x, 9)
00111010 <- rotr(x, -1)
01000111 <- rotr(x, 2)

另见

(C++20)
计算按位左旋转的结果
(函数模板)
反转整数中的位
(函数模板)
执行二进制左移和右移
(公开成员函数,属于 std::bitset<N>)