Skip to content

Commit 6073a1f

Browse files
Update setbits.c
follows the bit manipulation style (p as MSB of the field) as demonstrated in K&R, particularly aligning with the getbits example (p+1-n). So bits to be set are the least after the position p.
1 parent 2f1fed8 commit 6073a1f

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

chapter_2/exercise_2_06/setbits.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ unsigned int setbits(int x, int p, int n, int y)
2828
{
2929
++p; // First position is 0
3030

31-
unsigned int mask1 = (~(~(~0 << n) << p) & x);
32-
unsigned int mask2 = (~(~0 << n) & y) << p;
31+
unsigned int mask1 = (~(~(~0 << n) << (p-n)) & x);
32+
unsigned int mask2 = (~(~0 << n) & y) << (p-n);
3333

3434
return mask1 | mask2;
3535
}

0 commit comments

Comments
 (0)