Rotate Left in an 8-bit Register

Code

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

uint8_t rotate_left(uint8_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 % 8;

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

    // Calculate the bits that will wrap around from the left to the right
    // These are the 'n' most significant bits
    unsigned char wrapped_bits = reg >> (8 - n);

    // Calculate the remaining bits that are shifted left
    // The bits that "fall off" the left end are naturally discarded by the type's size
    unsigned char shifted_bits = reg << n;

    // Combine the shifted bits with the wrapped bits
    reg = shifted_bits | wrapped_bits;

    return reg;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

176 1

Expected Output

97