Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...