diff options
Diffstat (limited to '2')
| -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 |
