31. Rotate Left in an 8-bit Register

Back To All Submissions
Previous Submission
Next Submission

Code

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

uint8_t rotate_left(uint8_t reg, uint8_t n) {
    // Your code here

/* better solution when you shift  you insert zeros in lower bits equal to number of shiftds which is n
    so (reg << n) but these n lower bits should be set to n upper bits if we shift right n times we dont reach them we reahc 8-n example
    1101 1000 n= 2 -> 0011 0000 to set the lower bits to 11 shift the base 2 to right we get 000 1100  the 11 upper bits is not represented in lower 2 bits
    so what we do shift to right n-8 this brings lower bits 11 to lower bits 0000 0011 
    or the results we get the full rotation and to make sure no roation is above 8 use modulo so that 0%8 =1 1%8=2, ... 8%8 = 0... 9%8 =1 10%8=2, 
    
        n %= 8;
    return (reg << n) | (reg >> (8 - n));
    */.

    uint8_t mask = 0x80;

    for ( int i =0; i <n ; i++){
        if ( reg & mask ){
            reg = reg << 1;
            reg |= 1;
        }
        else if ( (reg & mask ) != 1)
            reg =reg << 1;
        }
    return reg;
}



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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote