summaryrefslogtreecommitdiffstats
path: root/2/7.c
blob: e35ec2eb5f68f4ce70d81d53716507387b4c0bb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>

/* inverts n bits of x starting at p */
unsigned invert(unsigned x, int p, int n);

int main(int argc, char * argv[]) {
    return 0;
}

unsigned invert(unsigned x, int p, int n) {
  unsigned xUnset, xSet, xInv;

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

  // mask to extract bits to invert:
  xSet = ~xUnset;

  // mask out x and copy inverted bits into unset bits:
  xInv = (x & xUnset) | ~(x & xSet);

  return xInv;
}