8. Set Specific Bits in a 32-bit Register

Discussions5
Log in to post comments and replies.
You
Loading editor...
KangajanKuganathan
#include <stdio.h>
#include <stdint.h>

uint32_t set_bits(uint32_t reg, uint8_t pos, uint8_t len) {
    // Your code here
    while (len) {
        reg |= (1 << pos);
        pos++;
        len--;
    }
    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;
}
0
MohammedYusuf
MohammedYusuf
Jul 14 2026

for (int i = 0; i < len; i++) {

        reg |= (1 << (pos + i));

    }

    return reg;

0
LishaSweetha
LishaSweetha
Apr 29 2026

   for(int i = 0; i < len; i++)

    {

        reg = reg | (1 << pos);

        pos++;

    }

0
GauthamShankar
GauthamShankar
Jul 07 2026

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

0
MohanKilari
MohanKilari
Dec 05 2025

#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;

}

0