summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSadeep Madurange <smadurange@users.noreply.github.com>2021-11-30 20:52:59 +0800
committerSadeep Madurange <smadurange@users.noreply.github.com>2021-11-30 20:52:59 +0800
commit38b5d067f60d752ac5b64612356558202e12d43e (patch)
treeba71b982d049c14de673092eeb5b17006639fcaf
parent025189ebf4a9543bc0d1f9c8dd880762f0d4a2ed (diff)
downloadk&r-exercises-38b5d067f60d752ac5b64612356558202e12d43e.tar.gz
2.7
-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