位旋转功能

时间:2018-04-23 13:54:44

标签: c++

我正在上一个调用创建一个名为Rotation的函数的在线类,该函数将获取一个对象并将其旋转计数位数。这是我目前的代码

unsigned Rotate(unsigned object, int count)
{  
   /*Initialize number of bits*/
   int numOfBits = CountBits(); 

   if (count < 0)
   {
      /*Negate count if it was a negative value*/
      count = -count;

      return (object << count) | (object >> (numOfBits - count));
   }
   else
      return (object >> count) | (object << (numOfBits - count));
}

CountBits的代码是:

const int SHIFT_COUNT = 1;  //Set bit shift count to 1

    int CountBits()
    {
       unsigned int uiValue = 1;  //Initial value to shift bits
       int bitCount;              //Variable to store the bit count

       /*Left-shift one bit at a time until the value equals zero*/
       for (bitCount = 0; uiValue != 0; bitCount++)
          uiValue <<= SHIFT_COUNT;

       return bitCount;
    }

我相信我的代码在前两个测试中正常工作,它会旋转1和-1。但是,当(numOfBits - count)为负数或大于对象的宽度时,我会标记为更改违规错误:

32位对象移位(&gt;&gt;)3217位

对象移位(&lt;&lt;)-3185位

在上面的代码中是否应该以特定方式处理这些类型的转换?

2 个答案:

答案 0 :(得分:2)

您不应该移动超过对象的大小。这意味着你应该将传递的数字包装在限制中] -numOfBits; numOfBits [,因为-numOfBits的旋转+ numOfBits只是一个无操作。

代码可能变成:

unsigned Rotate(unsigned object, int count)
{  
   /*Initialize number of bits*/
   int numOfBits = CountBits(); 

   count %= numOfBits;

   if (count < 0)
       ...

答案 1 :(得分:0)

超过对象大小的位移是未定义的行为。符合规定的程序不得调用未定义的行为。

但是,我们知道当我们按对象的大小旋转时,我们最终会得到原始对象,因此我们只需要移动{ "compilerOptions": { "target": "es5", "module": "commonjs", "moduleResolution": "node", "sourceMap": true, "emitDecoratorMetadata": true, "experimentalDecorators": true, "lib": [ "es2015", "dom" ], "noImplicitAny": true, "suppressImplicitAnyIndexErrors": true } } 残差 modulo 对象大小:

count