Rotate Right in a 32-bit Register

Code

#include <stdio.h>
#include <stdint.h>

uint32_t rotate_right(uint32_t reg, uint8_t n) {
     // Normalize n to be within the range [0, 7]
    // Rotating by n is the same as rotating by n % 8
    n = n % 32;

    // Handle the case where n is 0 to avoid shifting by 8 (which is undefined behavior for right shift)
    if (n == 0) {
        return reg;
    }

    // Combine the shifted bits with the wrapped bits
    reg = (reg >> n) | (reg << (32 - n));

    return reg;
}

int main() {
    uint32_t reg;
    uint8_t n;
    scanf("%u %hhu", &reg, &n);
    printf("%u", rotate_right(reg, n));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

2147483648 1

Expected Output

1073741824