1

我正在尝试编写一个位旋转器函数​​,并且我正在尝试对 sizeof 运算符进行更多说明。由于我不知道需要旋转哪种类型的数值对象,我假设我需要使用 sizeof 运算符

unsigned rotator(unsigned object, int count)

此函数原型,其中 object 是要旋转的对象, count 是要移动的位数。我想象如果我有一个 8 位数,我首先会确定要旋转的实际位数(因为这个人可以使 count = 20 例如,所以我会做类似的事情:

int actualBitRotation;
if (count > sizeof(object)) {
    actualBitRotation = count % sizeof(object);

但我认为我仍然没有正确理解 sizeof 。我确实尝试阅读有关它的在线资源,并在另一个问题上从该板获得了一些帮助,但我认为我没有得到它。我知道 sizeof 返回对象中的字节数,所以我会包括而不是做更多类似的事情

int actualBitRotation;
if (count > (sizeof(object) * CHAR_BIT) {
    actualBitRotation = count % (sizeof(object) * CHAR_BIT);
}

谢谢!

4

2 回答 2

3

sizeof() 确实返回字节数,因此您需要乘以 CHAR_BIT 以获得位数。

template<typename T> T bitrot(T& t,size_t bits) {
   bits %= (sizeof(T)*CHAR_BIT);
   return ((t >> (sizeof(T)*CHAR_BIT)-bits) | (t << bits));
}

澄清一下,您应该始终避免移位操作超出变量中的位数;结果取决于处理器和编译器。

于 2010-01-19T23:45:05.893 回答
0

怎么样:

union hack {
    int asSigned;
    unsigned asUnsigned;
};
hack top, bottom;
int realBitCount = count % (sizeof(T)*8);
top.asSigned = (realBitCount == 0) ? 0 : -(1 << (realBitCount-1));
bottom.asUnsigned = 0xFFFFFFFF ^ top.asUnsigned;

top.asUnsigned &= object;
bottom.asUnsigned &= object;
return static_cast<T>( (bottom.asUnsigned << realBitCount) | (top.asUnsigned >> (sizeof(T)-realBitCount)) );
于 2011-09-13T00:34:46.213 回答