📜  C ++程序旋转数字的位

📅  最后修改于: 2022-05-13 01:54:35.860000             🧑  作者: Mango

C ++程序旋转数字的位

位旋转:旋转(或循环移位)是一种类似于移位的操作,不同之处在于将一端脱落的位放回另一端。
在左旋转中,在左端脱落的位被放回右端。
在右旋转中,在右端脱落的位被放回左端。

例子:
让 n 使用 8 位存储。将 n = 11100101 左旋转 3 使 n = 00101111 (左移 3 位,前 3 位放回 last )。如果 n 使用 16 位或 32 位存储,则 n (000…11100101) 的左旋转变为 00..00 11100101 000。
如果 n 使用 8 位存储,则将 n = 11100101 右旋转 3 使得 n = 10111100 (右移 3 并且最后 3 位首先放回)。如果 n 使用 16 位或 32 位存储,则 n (000…11100101) 右旋转 3 变为101 000..00 11100

C++
// C++ code to rotate bits 
// of number
#include
  
using namespace std;
#define INT_BITS 32
class gfg
{
      
/*Function to left rotate n by d bits*/
public:
int leftRotate(int n, unsigned int d)
{
      
    /* In n<>(INT_BITS - d) */
    return (n << d)|(n >> (INT_BITS - d));
}
  
/*Function to right rotate n by d bits*/
int rightRotate(int n, unsigned int d)
{
    /* In n>>d, first d bits are 0. 
    To put last 3 bits of at 
    first, do bitwise or of n>>d
    with n <<(INT_BITS - d) */
    return (n >> d)|(n << (INT_BITS - d));
}
};
  
/* Driver code*/
int main()
{
    gfg g;
    int n = 16;
    int d = 2;
    cout << "Left Rotation of " << n << 
            " by " << d << " is ";
    cout << g.leftRotate(n, d);
    cout << "
Right Rotation of " << n <<
            " by " << d << " is ";
    cout << g.rightRotate(n, d);
    getchar();
} 
  
// This code is contributed by SoM15242


输出 :

Left Rotation of 16 by 2 is 64
Right Rotation of 16 by 2 is 4

有关更多详细信息,请参阅有关旋转位数的完整文章!