Clear Specific Bits in a 32-bit Register

Code

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

uint32_t clear_bits(uint32_t reg, uint8_t pos, uint8_t len) {
    // 1. Create a mask with 'len' bits set to 1
    // 2. Shift it to the starting position 'pos'
    // 3. Invert it so the bits to clear are 0 and others are 1
    // Note: (1U << len) - 1 creates a block of 1s of length 'len'
    
    // Handle the edge case where len is 32 to avoid undefined behavior with shifts
    if (len == 0) return reg;
    
    uint32_t mask;
    if (len >= 32) {
        mask = 0xFFFFFFFF;
    } else {
        mask = ((uint32_t)1 << len) - 1;
    }
    
    mask = ~(mask << pos);
    
    return reg & mask;
}

int main() {
    uint32_t reg;
    uint8_t pos, len;
    
    // Using %u for 32-bit unsigned and %hhu for 8-bit unsigned
    if (scanf("%u %hhu %hhu", &reg, &pos, &len) == 3) {
        printf("%u\n", clear_bits(reg, pos, len));
    }
    
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

255 4 4

Expected Output

15