Under normal circumstances, you can only ask for a bit rotation using assembly code, however, it is possible to imitate rotation through code.
First an explanation on rotating, and bits:
Bits, make up bytes. When represented in binary, a bit can be either a 1, or a 0. Nothing more. A byte, is a bunch of bits in a string, i.e: 0101 (which is actually the number 5, but I won’t get into that now.)
Now rotating a byte, say, 0110, requires one thing: a direction. So if we were to rotate that byte, to the left, the 0 on the lefternmost side, would come off the front, and fly around until sticking itself on the back, as such:
“1100″
If we were to take the original byte, and rotate it to the RIGHT instead, that other 0 would fly around to the back:
“0011″
For more info, and images describing this visit: wikipedia.
Now, keep in mind that code that they have there is PARTIALLY right. However it is mostly wrong.
Doing the operation that it describes would turn a byte that looks like 0100, into 1010, no matter which way you “rotate” it. That is not a proper rotation, especially when you only tend to shift by one bit at a time.
There is a simpler way, I’ve discovered, and it only involves basic shifting, a mask, and a few logic operations. Check it:
unsigned int rotateLeft( unsigned int i ) { //If there's a bit on the very front, it's gonna come around to the end. if( i >= 0x80000000 ) { i < <= 1; i++; //Which is why we add 1. } else //Otherwise, it's just a simple shift, as a 0 will be put at the end. { i <<= 1; } return i; } unsigned int rotateRight( unsigned int i ) { //It's odd, so a bit is gonna come around to the front. if( i%2 == 1 ) { i >>= 1; i ^= 0x80000000; //This flips that front bit from a 0, to a 1. } else //Otherwise again, just a simple shift. { i >>= 1; } return i; }
Nota bene: They have to use unsigned integers, because otherwise you risk flipping a bit while rotating which will make it negative, and then it’ll be unrotated the completely wrong way. More on this later though, right now, I’m sleepy after wrestling with this for half the day.
