Rotate Left in an 8-bit Register

Code

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

uint8_t rotate_left(uint8_t reg, uint8_t n) {
    // Your code here
    uint8_t bitl=0;
    uint8_t regl=0;
    for(int i =0; i<n;i++){
        regl=regl<<1;
        bitl=(reg&0x80)?1:0;
        //printf("%u\n",bitl);
        regl|=bitl;
        //printf("%u\n",regl);
        reg=reg<<1;
        //printf("%u\n",reg);

    }
    //printf("%u\n",regl);
    reg|=regl;

    return reg;
}

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

Solving Approach

First check whether the bit is 1 or 0. Then accordingly create another variable(regl) and using for loop push the elements to that variable and also left shift the  original variable (reg) afther the for loop append regl to reg.

Note 
1. To retrieve the bit: bitl=(reg&0x80)?1:0;

2. left shift regl on the top of the for loop. basically the rule is you have to create space(left shift) and then append the bit not append the bit and then (left shift/create space)

 

Upvote
Downvote
Loading...

Input

176 1

Expected Output

97