如何旋转给定数字的位?

时间:2014-08-11 18:24:10

标签: c++ c rotation bits

如何在运行时旋转给定数字的位,输入转数?

例如:

binary:    10000000000000000000000000001011
rotations: 3 times right
result:    01110000000000000000000000000001

类似地:

binary     10000000000000000000000000001011
rotations: 4 times left
result:    00000000000000000000000010111000

下面是我要交换的代码,但我找不到旋转位的逻辑。

#include<stdio.h>
int main()
{
    int num,bitleft,bitright,i,j;
    printf("enter ur number\n");
    scanf("%d",&num);

    for(i=31,j=0;i>j;i--,j++) 
    {
        bitleft=num>>i&1;  //storing bits in integer from left
        bitright=num>>j&1;  //storing bits in integer from right
        if(bitleft!=bitright) // checking if bits are not similarly
        {
            num=num^1<<i; // not similar then complement
            num=num^1<<j;

        }
    }
    printf("\n");

    for(j=31;j>=0;j--)  // loop to print swapped bits
    {
        if(num&1<<j)
            printf("1");
        else
            printf("0");
    } 
}

1 个答案:

答案 0 :(得分:2)

试试这个:

#include <iostream>

template <typename T>
T rol_(T value, int count) {
    return (value << count) | (value >> (sizeof(T)*CHAR_BIT - count));
}

template <typename T>
T ror_(T value, int count) {
    return (value >> count) | (value << (sizeof(T)*CHAR_BIT - count));
}

int main() {
    unsigned int a = 0x8000000B; // 10000000000000000000000000001011 in binary
    std::cout << "A = 0x" << std::hex << a << ", ror(A, 3) = 0x" << ror_(a, 3) << std::endl;
    std::cout << "A = 0x" << std::hex << a << ", rol(A, 3) = 0x" << rol_(a, 3) << std::endl;
    return 0;
}

注意:

    rol 中的
  • (value << count) ror 中的(value >> count)设置 rol 中的高位和低位的 ROR 即可。其他的一点都消失了。
  • rol 中的
  • (value >> (sizeof(T)*CHAR_BIT - count)) ror 中的(value << (sizeof(T)*CHAR_BIT - count))设置上一操作中丢失的位。

示例(假设类型为32位):

binary:               10000000000000000000000000001011
rotations: 3 times right
(value >> 3):         00010000000000000000000000000001
(value << (32 - 3)):  01100000000000000000000000000000
------------------------------------------------------
                      01110000000000000000000000000001