Aug 12, 2015

Rotate left or right in C

In assembly there are direct instructions for rotate left and rotate right. But in C there is no straight forward method to do so. Here is a snippet that will let you do just that. And the best part is that, PIC C compiler will automatically know what you are trying to do and will replace this line of C with the corresponding assembly instruction.

val = ( (val >> 1) | (val << 7) );


The val << 7 is used as I assumed a 8 bit variable is being rotated. If you were to rotate a 16 bit value , use vat << 15 instead.

For a generalized code, I have created a macro:

Rotate right by a bit:
# define BitRotRgt(x)   x = (x>>1)|(x<<((sizeof(x)*8)-1))


Rotate left by a bit:
# define BitRotLft(x)    x = (x<<1)|(x>>((sizeof(x)*8)-1))



No comments:

Post a Comment