How to rotate the bits in a word

最后都变了- 提交于 2019-12-02 03:33:18

问题


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.


回答1:


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




回答2:


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:


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.



来源:https://stackoverflow.com/questions/4207546/how-to-rotate-the-bits-in-a-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!