Skip to content

Commit 79329fb

Browse files
committed
fix answer
1 parent 85e64d7 commit 79329fb

File tree

1 file changed

+12
-10
lines changed

1 file changed

+12
-10
lines changed

chapter02/2-6.c

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2,30 +2,32 @@
22
* Exercise 2-6. Write a function setbits(x,p,n,y) that returns x with the n
33
* bits that begin at position p set to the rightmost n bits of y, leaving the
44
* other bits unchanged.
5+
*
56
* by Faisal Saadatmand
6-
* */
7+
*/
78

89
#include <stdio.h>
910

1011
/* functions */
11-
unsigned int setbits(unsigned int, int, int, unsigned);
12+
unsigned int setbits(unsigned, int, int, unsigned);
1213

13-
unsigned int setbits(unsigned int x, int p, int n, unsigned y)
14+
unsigned int setbits(unsigned x, int p, int n, unsigned y)
1415
{
15-
unsigned mask = ~(~0 << n); /* mask to extract n bits from y */
16-
unsigned xORy;
16+
unsigned nbits;
1717

18-
xORy = x | (y & mask) << p; /* move bits to p, OR with x to set them */
19-
return xORy;
18+
nbits = ~(~0 << n); /* mask to extract rightmost n bits */
19+
20+
return (x & ~(nbits << p)) | ((y & nbits) << p);
2021
}
2122

2223
int main(void)
2324
{
24-
unsigned int x = 0XF8FF;
25-
unsigned int y = 0XF0A2;
25+
unsigned x = 0XF8FF;
26+
unsigned y = 0XF0A2;
2627
int p = 8; /* starting position of bits */
27-
int n = 2; /* number of bits to set */
28+
int n = 8; /* number of bits to set */
2829

2930
printf("%x\n", setbits(x, p, n, y));
31+
3032
return 0;
3133
}

0 commit comments

Comments
 (0)