I need to implement a function that rotates left the last 10 bits of an int.
So if an int has value
0b 1111 0000 0000 0000 0000 1100 1100 0000
a left rotation by 2 would give us
0b 1111 0000 0000 0000 0000 1111 0000 0000
A further left rotation by 1 would give
0b 1111 0000 0000 0000 0000 1110 0000 0001
ptr
- pointer to given int that we want to rotaten
- how many times we want to rotate
void leftRotateLast10Digits(int * ptr, int n) {
}
I understand how to do it if we wanted to rotate the whole int, but I'm not sure how to do it for the last 10 digits only. I think to left rotate an int, it would look something like below. But still, I don't understand how to only rotate the last 10 digits.
void leftRotate(int * ptr, int n) {
int DROPPED_MSB;
int INT_BITS = sizeof(int) * 8 - 1;
int num = *ptr;
// The effective rotation
n %= INT_BITS;
while(n) {
DROPPED_MSB = (num >> INT_BITS) & 1;
// Left rotate num by 1 and set its dropped MSB as new LSB
num = (num << 1) | DROPPED_MSB;
n--;
}
*ptr = num;
}
A relatively easy way to do this would be to separate the integer into two parts: the 10 bits that should be rotated and the other (upper) bits that shouldn't be rotated. Then, after rotating the appropriate part, restore the other bits using a bitwise OR operation: