Clear Specific Bits in a 32-bit Register

 

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

uint32_t clear_bits(uint32_t reg, uint8_t pos, uint8_t len) {
    // Your code here
    /*
    For a len of 32, the mask is set to 0xFFFFFFFF (all bits 1).
    For other len, the mask is created by shifting 1 left by len positions and 
    subtracting 1, resulting in len consecutive 1s at the least significant bits.
    Shift the created mask left by the starting position (pos) to align it with the 
    target bits in the register. 
    Perform a bitwise AND between the original register and the negation of the shifted mask to set the specified bits to 0.
 
    */
    uint32_t mask = ((len == 32) ? 0xFFFFFFFF : ((1u << len) - 1) << pos);
    return reg & ~mask ;
}

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

 

 

 

 

Loading...

Input

255 4 4

Expected Output

15