Search code examples
bit-manipulationpicdspic

How to rotate the bits in a word


I'm using a dsPIC33F and GCC. I want to rotate the bits in a word once left or right, like this:

       MSB             LSB
input: 0101 1101 0101 1101
right: 1010 1110 1010 1110
left : 1011 1010 1011 1010

(In case it's not clear, the LSB moves into the MSB's position for the right rotate and vice versa.)

My processor already has a rotate right (rrnc, rrc) and rotate left instruction (rlnc, rlc), so I'm hoping the compiler will optimise this in. If not, I might have to use inline assembly.


Solution

  • You may write them as obvious combination of conventional shifts:

    x rol N == x << N | x >> width-N
    x ror N == x >> N | x << width-N
    

    where width is number of bits in number you rotate.

    Intelligent compiler may (i think it would be) detect this combination and compile to rotation instruction.

    Note it works for unsigned and if width is equal to number of bits in machine word you are dealing on (16 for unsigned int on dsPIC).