Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

bit-shift

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.

like image 890
Miroslav Cetojevic Avatar asked Jul 09 '11 21:07

Miroslav Cetojevic


1 Answers

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.

like image 76
Mario Avatar answered Sep 21 '22 01:09

Mario