开发者

Rotating Bits, using sizeof operator

I'm trying to write a bit rotator function and I'm trying to get more clarification the sizeof operator. Since I don't know what type of numerical object I need to rotate, I assume I need to use the sizeof operator for

unsigned rotator(unsigned object, int count)

this function prototype where object is the object to be rotated and count is the number of bits to be moved. I am imagining that if I had an 8 bit number, I first would determine the actual number of bits to be rotated (since the person can make count = 20 for example, so I would do something like:

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

But I don't think I understand sizeof correctly still. I did try reading online resources about it and have received some help from this board on it with another problem, but I don't think I get it. I know sizeof returns the number of bytes in the object, so would I include and instead do something more like

int actualBitRotation开发者_运维百科;
if (count > (sizeof(object) * CHAR_BIT) {
    actualBitRotation = count % (sizeof(object) * CHAR_BIT);
}

Thanks!


sizeof() does return the number of bytes so you need to multiply by CHAR_BIT to get the number of bits.

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

To clarify, you should always avoid shifting operations beyond the number of bits in the variable; the results are processor- and compiler- dependent.


how about:

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)) );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜