Blame


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