All submissions

Clear Specific Bits in a 32-bit Register

Solution with Approach

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

uint32_t clear_bits(uint32_t reg, uint8_t pos, uint8_t len) {
    // Your code here
    uint32_t mask = (1U << len)-1;
    reg &= ~(mask << pos);
    return reg;
}

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

Example: pos =4, len =3;

  1. Create Mask:  
    • mask = (1U << len) - 1 = 0b111
  2. Shift the mask to the required position:
    • mask << pos = 0b1110000
  3. Invert all the bits: this creates mask toall bits except the ones to be cleared.
    • ~(mask << 4) = 11111111 11111111 11111111 10001111
  4. AND it with the reg to see the changes in only in the given range.
    • reg &= ~(mask << 4)

 

 

 

Loading...

Input

255 4 4

Expected Output

15