Split it up some:
Code:
// Assume x = 10010011 (binary), p = 3 (decimal), n = 2 (decimal), y = 11001010 (binary)
// Also assume rightmost bit (LSB) is position 1.
uint8_t setbits(uint8_t x, uint8_t p, uint8_t n, uint8_t y)
{
uint8_t mask;
uint8_t temp;
mask = ~0; // All bits set (mask = 11111111)
mask >>= 8 - n; // n bits set in lowest position (mask = 00000011)
temp = y & mask; // set to first n bits of y (temp = 00000010)
temp <<= p - 1; // set to n bits of y at position p (temp = 00001000)
mask <<= p - 1; // n bits set at position p (mask = 00001100)
x &= ~mask; // n bits at position p cleared (x = 10010011)
x |= temp; // x set to first n bits of y at position p (x = 10011011)
return x;
}