【问题标题】:How to rotate the bits of given number? [duplicate]如何旋转给定数字的位? [复制]
【发布时间】:2014-10-04 16:10:46
【问题描述】:

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

例如:

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");
    } 
}

【问题讨论】:

  • @user3859409 “运行时没有旋转”是什么意思?
  • Wikipedia 提供了一个非常干净的实现
  • 博士;可能相关:stackoverflow.com/questions/776508/…
  • 要将num 向左旋转k 位,请写入(num &lt;&lt; k) | (num &gt;&gt; (sizeof(num)*CHAR_BIT - k))
  • 尽可能使用asm("...")

标签: c++ c rotation bits


【解决方案1】:

试试这个:

#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 &lt;&lt; count)ror 中的(value &gt;&gt; count) 设置 rol 中的高位和 ror 中的低位>。其他部分消失了。
  • rol 中的(value &gt;&gt; (sizeof(T)*CHAR_BIT - count))ror 中的(value &lt;&lt; (sizeof(T)*CHAR_BIT - count)) 设置在先前操作中丢失的位。

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

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

【讨论】:

  • 我正在寻找不使用任何内置函数或任何库的解决方案
  • 使用 sizeof(T) 和 CHAR_BIT 更新了代码。
猜你喜欢
  • 1970-01-01
  • 2021-10-06
  • 2021-06-27
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多