Reputation: 652
"Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions."
Just to clarify if I'm understanding this correctly, this is asking me to bring bits that are shifted out of the bit size on the right to re-appear on the left. For example, with 8-bits:
10111001
>> 2
01101110
Upvotes: 0
Views: 722
Reputation: 154198
Yes, K&R exercise 2.8 is a rotate right (not through carry).
All sort of shifts may be implemented:
Logical shifts: right
Shift each bit to the next least significant position. The LSBit is discarded. The MSbit becomes 0.
unsigned x; x >>= 1;
Logical shifts: left
Shift each bit to the next most significant position. The MSBit is discarded. The LSBit becomes 0.
unsigned x; x <<= 1;
Rotate shifts: left
Shift each bit to the next most significant position. The MSBit becomes the LSBit.
unsigned x; x = (x << 1) | x >> (sizeof x * CHAR_BIT - 1);
Rotate shifts: right
Shift each bit to the next least significant position. The LSBit becomes the MSBit.
unsigned x; x = (x >> 1) | x << (sizeof x * CHAR_BIT - 1);
Arithmetic shift: left
Shift each bit to the next most significant position. The LSBit become 0. Should the MSBit (sign bit) change, different machines handle this is different ways. Thus that is UB.
[Assuming 2's complement]
int x; x <<= 1
Arithmetic shift: right
Shift each bit to the next least significant position. The MSBit remains the same. The LSBit is discarded.
[Assuming 2's complement]
int x; x >>= 1;
Other shifts/rotates work through the carry bit, but that is more of a hardware level function.
Upvotes: 1
Reputation: 815
Maybe you don't need this but to try and anticipate further questions I'll add. In the example you gave, rotating by 8 or 16 is the same as not rotating at all and so the mod operator will be of use.
Upvotes: 1