Rotating a value left....
Expand
Left rotation:
Lets take an example of an 8-bit unsigned value.
Rotation of bits is nothing but shifting without loosing bits.
ex: value = 10101101
To rotate this number to left we must know what is the MSB. Doing 1 left shift removes this bit and adds one 0 to LSB. Rotation is possible if we could add 1 instead of 0 at LSB. If MSB is 0 then no need to add anything.
So steps are:
1. Check MSB
2. If MSB = 1 if((value & (1<<7) )== (1<<7))
Do left shift value<<1
Do bitwise OR (|)
to the shifted value by 1 value = value | 1
3. else
Do left shift value<<1
4. print value
5 loop 2 to 4 as many times as needed to rotate value those many times
To generalize this take shift value not as 7 but n-1 where n is sizeof(type) - 1
Ex: n = sizeof(int) - 1;
Right rotation:
Check LSB before shifting :-)
Close