位旋转功能

  • 本文关键字:功能 旋转 c++
  • 更新时间 :
  • 英文 :


我正在上一个在线类,该类调用,以创建一个称为旋转的函数,该函数将吸收一个对象并旋转其计数位数。这是我当前有

的代码
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位对象被3217位移动(>>(

对象移动(&lt;&lt;(by -3185位

在我的上述代码中应处理这些类型的班次的特定方式?

您不应该移动超过对象的大小。这意味着您应该将传递的数字包裹在限制中] -numofbits;numofbits [,因为-numofbits的旋转 numofbits只是一个no -op。

代码可以变为:

unsigned Rotate(unsigned object, int count)
{  
   /*Initialize number of bits*/
   int numOfBits = CountBits(); 
   count %= numOfBits;
   if (count < 0)
       ...

比对象大小的位移动是未定义的行为。符合程序不得调用不确定的行为。

但是,我们知道,当我们通过对象的大小旋转时,我们最终都会使用原始对象,因此我们只需要通过 count modulo的 resceue 移动 modulo 对象大小:

#include <limits.h>
unsigned Rotate(unsigned object, int count)
{
    static const int max_bits = sizeof object * CHAR_BIT;
    count %= max_bits;
    if (!count)
        /* avoid undefined shift right */
        return object;
    if (count < 0)
        /* force a positive quotient */
        count += max_bits;
    return (object << count) | (object >> (max_bits - count));
}
int main()
{
    unsigned u = 0xFF00;
    unsigned v = Rotate(u, 260); /* 256 + 4 */
    return v != 0xFF000;
}

最新更新