summaryrefslogtreecommitdiffstats
path: root/2/6.c
blob: bf8cf2f0a1f1c7d912843c89473795cdcdb0a101 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>

unsigned setbits(unsigned x, int p, int n, unsigned y);

int main(int argc, char *argv[]) {
  int p, n;
  unsigned x, y;

  p = 5;
  n = 3;
  x = 0;
  y = 7;

  printf("New bit field: %x\n", setbits(x, p, n, y));

  return 0;
}

unsigned setbits(unsigned x, int p, int n, unsigned y) {
  unsigned yLO, yLOA, xUnset, xPrime;

  // extract n LO bits from y
  yLO = y & ~(~0 << n);

  // align extracted bits to p:
  yLOA = yLO << (p + 1 - n);

  // mask to unset n bits starting at p:
  xUnset = (~0 << p) | ~(~0 << (p - n));

  // mask out x:
  xPrime = x & xUnset;

  return xPrime | yLOA;
}