Blob


1 /*
2 * 2-6. Write a function setbits(x,p,n,y) that returns x with the n bits
3 * that begin at position p set to the rightmost n bits of y, leaving the
4 * other bits unchanged.
5 */
7 #include <stdio.h>
9 unsigned setbits(unsigned x, int p, int n, unsigned y);
10 unsigned getbits(unsigned x, int p, int n);
12 main()
13 {
14 printf("%u: %u\n", 0xabcdf211, setbits(0xabcdef01, 12, 9, 0x87654321));
15 printf("%u: %u\n", 0x1ff45678, setbits(0x12345678, 27, 7, 0xffffffff));
16 printf("%u: %u\n", 0x92fab07a, setbits(0x92fab3da, 9, 5, 0x182b3da3));
17 printf("%u: %u\n", 0x1ba95e6a, setbits(0x1ba83dea, 17, 11, 0x29eb3abc));
18 }
20 unsigned setbits(unsigned x, int p, int n, unsigned y)
21 {
22 return ((x >> (p+1)) << (p+1)) | (getbits(y, n-1, n) << (p-n+1)) | (x & ~(~0 << (p-n+1)));
23 }
25 /*
26 0 0000 1 0001 2 0010 3 0011 4 0100
27 5 0101 6 0110 7 0111 8 1000
28 a 1010 b 1011 c 1100 d 1101 e 1110 f 1111
29 x 1010 1011 1100 1101 1110 1111 0000 0001
30 y 1000 0111 0110 0101 0100 0011 0010 0001
31 1010 1011 1100 1101 1111 0010 0001 0001
32 a b c d f 2 1 1
34 x 0001 0010 0011 0100 0101 0110 0111 1000
35 y 1111 1111 1111 1111 1111 1111 1111 1111
36 0001 1111 1111 0100 0101 0110 0111 1000
37 1 f f 4 5 6 7 8
39 x 1001 0010 1111 1010 1011 0011 1101 1010
40 y 0001 1000 0010 1011 0011 1101 1010 0011
41 1001 0010 1111 1010 1011 0000 0111 1010
42 9 2 f a b 0 7 a
44 x 0001 1011 1010 1000 0011 1101 1110 1010
45 y 0010 1001 1110 1011 0011 1010 1011 1100
46 0001 1011 1010 1001 0101 1110 0110 1010
47 1 b a 9 5 e 6 a
48 */
50 unsigned getbits(unsigned x, int p, int n)
51 {
52 return (x >> (p+1-n)) & ~(~0 << n);
53 }