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

2020-03-03 05:50发布

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.

标签: c bit-shift
2条回答
兄弟一词,经得起流年.
2楼-- · 2020-03-03 06:16

Right idea but the other way.

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

查看更多
beautiful°
3楼-- · 2020-03-03 06:19

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.

查看更多
登录 后发表回答