问题
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