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) {
    // In binary, subtracting 1 from a power of 2 always gives you all 1s in the lower positions. It's similar to how in decimal:
    // 1000 - 1 = 999
    // 100 - 1 = 99

    // Solution 1:
    uint32_t mask = ((0x1 << len) - 1) << pos;
    return (reg |= mask);
 
    // Solution 2:
    // for(uint32_t i = 0; i < len; i++){
    //     reg |= (0x1 << (pos + i));
    // }
    // 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

 

 

 

Upvote
Downvote
Loading...

Input

0 4 3

Expected Output

112