All submissions

Set Multiple Bits in 8-bit Register

 

 

Code

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

uint8_t set_range(uint8_t reg, uint8_t start, uint8_t end) {
    // Your code here
    for(uint8_t pos=start ; pos<=end ; pos++){
        reg = reg | 1<<pos;
    }
    return reg;
}

int main() {
    uint8_t reg, start, end;
    scanf("%hhu %hhu %hhu", &reg, &start, &end);
    printf("%u", set_range(reg, start, end));
    return 0;
}

Solving Approach

consider example 1.

Input: reg = 0b00000000, start = 1, end = 3 
Output: 0b00001110

my logic:

for(uint8_t pos=start ; pos<=end ; pos++){
        reg = reg | (1<<pos);
    }

1 . i am iterating the loop from start and end.

2. (1<<pos) --> here i am moving 1 to specific position. 

 reg | (1<<pos)  = pos = 1 -->  0000 0010

 reg | (1<<pos)  = pos = 2 -->  0000 0110

 reg | (1<<pos)  = pos = 3 -->  0000 1110

3.  reg | (1<<pos) --> here 1 or operation with the reg

after iteration reg is --> reg | (1<<pos)  is 0000 1110

reg -->                0000 0000

(1<<pos) -->     0000 1110

                          ---------------------

result      -->       0000 1110

                          ---------------------

Loading...

Input

0 1 3

Expected Output

14