Set Specific Bits in a 32-bit Register

Code

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

uint32_t set_bits(uint32_t reg, uint8_t pos, uint8_t len) {
    // Your code here

    reg |=  ((1<<len)-1 )<< pos;
    return reg;
}

int main() {
    uint32_t reg;
    uint8_t pos, len;
    scanf("%u %hhu %hhu", &reg, &pos, &len);
    printf("%u", set_bits(reg, pos, len));
    return 0;
}

Solving Approach

uint32_t set_bits(uint32_t reg, uint8_t pos, uint8_t len) {
    // Your code here

	reg |=  ((1<<len)-1 )<< pos;
    return reg;
}
uint32_t set_bits(uint32_t reg, uint8_t pos, uint8_t len) {
    // Your code here

    reg |=  ((1<<len)-1 )<< pos;
    return reg;
}
(1<<len)-1 :- here len is 3 left. 
		   :- shifting to 1  to 3 rd postion
		   :- this value is 8-1 (0111)

(7)<< pos  :- here pos is 4.
		   :- now 7 leftshifting to pos	so 0111 0000 
Upvote
Downvote
Loading...

Input

0 4 3

Expected Output

112