1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <stdio.h>
unsigned setbits(unsigned x,int p,int n,unsigned y);
int main()
{
// int x,p,n,y;
printf("setbits(x=0x%x, p=%d, n=%d, y=0x%x) => 0x%x\n",
0x1234, 15, 8, 0xffff, setbits(0x1234, 15, 8, 0xffff));
printf("setbits(x=0x%x, p=%d, n=%d, y=0x%x) => 0x%x\n",
0x1234, 14, 3, 2, setbits(0x1234, 14, 3, 2));
printf("setbits(x=0x%x, p=%d, n=%d, y=0x%x) => 0x%x\n",
0x1234, 20, 6, 0xf2, setbits(0x1234, 20, 6, 0xf2));
printf("setbits(x=0x%04x, p=%d, n=%d, y=0x%04x) => 0x%04x\n",
0x1234, 31, 4, 0x192f, setbits(0x1234, 31, 4, 0x192f));
printf("setbits(x=0x%X, p=%d, n=%d, y=0x%X) => 0x%04X\n",
0x1234, 8, 4, 0xE, setbits(0x1234, 8, 4, 0xE)); // 13D4
}
unsigned setbits(unsigned x,int p,int n,unsigned y)
{
// return x & ~(~(~0 << n) << (p+1-n)) | ( y & (~(~0<<n)) << (p+1-n));
int shift = p - n + 1;
unsigned mask = (1U << n) - 1;
return (x & ~(mask << shift)) | ((y & mask) << shift);
}
|