K&R - Understanding exercise 2-8: Exactly what is asked here?

别说谁变了你拦得住时间么 提交于 2019-12-19 03:17:51

问题


I'm working through the exercises in the K&R book. Currently I'm stuck at exercise 2-8, which is says the following:

Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n bit positions.

The trouble I have is that I cannot seem to picture what the result SHOULD look like.

How or what do I rotate? Do I take the leftmost bit and put it to the rightmost position of x, after x is shifted to the left and repeat this for n bits? Or do I take a chunk (n bits) and put it n bits to the right while leaving the rest of the rightmost bits unchanged?

Any helpful answer is appreciated. Thanks.


回答1:


Rotating means you're essentially shifting to the left or right but the bits otherwise "lost" will reappear on the other side.

It's a lot easier to explain with a decimal number:

Rotate 123456789 to the right by 3 digits will result in 789123456. Rotate 123456789 to the left by 4 digits will result in 567891234.

So you'll essentially take n bits from one side and attach them to the others. It's a lot easier to understand if you think of all digits sitting on a circle or wheel you're rotating around the center.

To avoid confusin just replace "rotate" with "move" or "shift" and don't forget to save the bits otherwise lost.




回答2:


Right idea but the other way.

Get rightmost bit. Shift right. Set the leftmost bit. Do this n times.



来源:https://stackoverflow.com/questions/6637578/kr-understanding-exercise-2-8-exactly-what-is-asked-here

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