Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
refactor setbits()
  • Loading branch information
isidroas committed Feb 16, 2025
commit 5a98acf3d242c9058df56345dddb24054f977df6
18 changes: 16 additions & 2 deletions chapter-2-types-operators-expressions/11.setbits.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,23 @@ main()

int setbits(int x, int p, int n, int y)
{
x = x & (~((~(~0 << n)) << (p - n + 1)));
y = (y & (~(~0 << n))) << (p - n + 1);
/* xxx............xxx x */
/* yyy...........ynnn y */

/* least significant position of the bits touched */
int r = p - n + 1;

/* 000...011110...000 mask */
/* p r ...210 position */
int mask = ~(~0 << p + 1) & (~0 << r);

/* 000...0nnnn0...000 */
y = (y << r) & mask;

/* xxx...x0000x...xxx */
x = x & ~mask;

/* xxx...xnnnnx...xxx */
return x | y;
}