tags:

views:

86

answers:

1

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!

+1  A: 

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.

Will
I think Crystal was asking about what happens if you rotate more then the number of bits in the int.So at the beginning of your bitrot() function put: bits = bits % (sizeof(T)*CHAR_BITS);