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) {
    // Your code here
    return (reg &= ( ~( ((1U<<len)-1) << pos) ));
}

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

Solving Approach

  1. To make sure we do not clear the other bits (Leave them untouched), we can AND with 1.

  2. To make the mask, lets create zero bits with the length specified, ((1U<<len)-1) gives all ones, then we left shift the ones to the position we want to clear before taking the inverse of that which is all zeros on the mask, and ones everywhere else.

  3. Now remember that AND-ing with 1 leaves the bit untouched and AND-ing with 0 clears the bit, so We clear the len number of bits while leaving the rest untouched.

 

 

Upvote
Downvote
Loading...

Input

255 4 4

Expected Output

15