summaryrefslogtreecommitdiffstats
path: root/2/7.c
diff options
context:
space:
mode:
Diffstat (limited to '2/7.c')
-rw-r--r--2/7.c25
1 files changed, 16 insertions, 9 deletions
diff --git a/2/7.c b/2/7.c
index e35ec2e..0c2ae6f 100644
--- a/2/7.c
+++ b/2/7.c
@@ -4,20 +4,27 @@
unsigned invert(unsigned x, int p, int n);
int main(int argc, char * argv[]) {
- return 0;
+ 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 xUnset, xSet, xInv;
+ unsigned mask, y;
// mask to unset n bits starting at p:
- xUnset = (~0 << p) | ~(~0 << (p - n));
-
- // mask to extract bits to invert:
- xSet = ~xUnset;
+ mask = (~0 << p) | ~(~0 << (p - n));
- // mask out x and copy inverted bits into unset bits:
- xInv = (x & xUnset) | ~(x & xSet);
+ // invert and extract bits:
+ y = ~(x & ~mask) & ~mask;
- return xInv;
+ // mask out x and copy inverted bits into x:
+ return (x & mask) | y;
} \ No newline at end of file