From 38b5d067f60d752ac5b64612356558202e12d43e Mon Sep 17 00:00:00 2001 From: Sadeep Madurange Date: Tue, 30 Nov 2021 20:52:59 +0800 Subject: 2.7 --- 2/7.c | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) (limited to '2') 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 -- cgit v1.2.3