Rotate Left in an 8-bit Register

Code

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

// Original   : 11010100 - > rotated: 110100110
// want to rotate left n = 3 bits
// 1. rotate left n = 3 bits: reg << 3 : 101000000
// 2. wrap right n = 3 bits: reg >>= (8 - 3) : 00000110
// 3. or them together: (reg << 3) | (reg >> (8 - 3))

// rotate left n bits
uint8_t rotate_left(uint8_t reg, uint8_t n) {
    
    // (shift left by n) | (wrap right by n)
    // drop first 3 bytes, filling in right with zeros
    // shift first 3 bytes ovr all the way to the end at the right
    // or them together

  return (reg << n) | (reg >> (8 - n));

}

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