diff options
| author | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-11-30 20:52:59 +0800 |
|---|---|---|
| committer | Sadeep Madurange <smadurange@users.noreply.github.com> | 2021-11-30 20:52:59 +0800 |
| commit | 38b5d067f60d752ac5b64612356558202e12d43e (patch) | |
| tree | ba71b982d049c14de673092eeb5b17006639fcaf /2/7.c | |
| parent | 025189ebf4a9543bc0d1f9c8dd880762f0d4a2ed (diff) | |
| download | k&r-exercises-38b5d067f60d752ac5b64612356558202e12d43e.tar.gz | |
2.7
Diffstat (limited to '2/7.c')
| -rw-r--r-- | 2/7.c | 25 |
1 files changed, 16 insertions, 9 deletions
@@ -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 |
