How to rotate the bits in a word

2019-02-26 03:41发布

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.

3条回答
贼婆χ
2楼-- · 2019-02-26 03:57

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.

查看更多
够拽才男人
3楼-- · 2019-02-26 03:57

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.

查看更多
三岁会撩人
4楼-- · 2019-02-26 04:16

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

查看更多
登录 后发表回答