All submissions

Replace Bit Field in a 32-bit Register

Code

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

uint32_t replace_field(uint32_t reg, uint32_t val, uint8_t pos, uint8_t len) {
    // Clear the field at position 'pos' with length 'len' and insert 'val'
    uint32_t mask = (((((~0U) << len) | val) << pos) | ((1U << pos) - 1));

    return reg & mask;

}

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

Solving Approach

  1. Take an unsigned 0 value and invert it to get all 1's or 0xFFFFFFFF for the mask

  2. Shift the current mask over by the 'len' of the value

  3. OR the previous mask with 'val' to place the value in the mask at the LSB

  4. Shift the previous mask over by 'pos' to get the 'val' in the right position in the mask

  5. Make a new mask that consists of an unsigned 1 in the LSB

  6. Shift the 1 over 'pos' times to match where the 'val' should be (Ex. 0000 1000)

  7. Subtract the previous mask by 1 to get 1's in all the positions prior to the 'pos' spot (Ex. 0000 0111)

  8. OR the previous mask with the mask from step 4 to get the final mask with the 'val' in the right position and not effecting other bits

  9. AND the final mask with the 'reg' to get the final result

 

Loading...

Input

255 0 4 4

Expected Output

15