summaryrefslogtreecommitdiffstats
path: root/2/7.c
blob: 0c2ae6f5dc77192eb2ffc08dbdee5fb62dba3691 (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
#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[]) {
  int n, p;
  unsigned x;

  n = 3;
  p = 5;
  x = 0xB7;

  printf("result: %x\n", invert(x, p, n));

  return 0;
}

unsigned invert(unsigned x, int p, int n) {
  unsigned mask, y;

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

  // invert and extract bits:
  y = ~(x & ~mask) & ~mask;

  // mask out x and copy inverted bits into x:
  return (x & mask) | y;
}