Question

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.

Was it helpful?

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).

OTHER TIPS

There is no circular shift in C. (Reference)

Inline assembly might be the way to go, if performance is critical. Otherwise you could use the code in the article linked above.

There is a GCC for dsPIC? Look in its manual if it has got an intrinsic for circular shifts. The other option is inline asm.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top