Rotate Left in an 8-bit Register

Code

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

/*
 * Function to rotate an 8-bit register left by n positions.
 */
uint8_t rotate_left(uint8_t reg, uint8_t n) {
    n %= 8; // Ensure rotation is within 0-7
    reg = ((reg << n) | (reg >> (8 - n)));

    return reg;
}

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

Solving Approach

This solution performs a circular left rotation on an 8-bit register by a specified number of positions. The rotation count is normalized to the 0–7 range using modulo operation. The function shifts the register left by the rotation count and right by the complement, then combines the results with a bitwise OR to achieve the circular effect. The main function reads the register and rotation count from input, applies the rotation, and prints the result. This approach ensures efficient and correct circular rotation for any input value.

 

 

Upvote
Downvote
Loading...

Input

176 1

Expected Output

97