Add exercise (2-7) Exercise 2-7: Write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.
1 files changed, 21 insertions(+), 0 deletions(-) A 2-7/invert.c
A 2-7/invert.c => 2-7/invert.c +21 -0
@@ 0,0 1,21 @@ #include <assert.h> /* invert: return x with the n bits that begin at position p inverted */ unsigned invert(unsigned x, int p, int n) { return x ^ (~(~0 << n) << (p - n + 1)); } /* check some examples */ int main() { assert(9 == invert(15, 2, 2)); /* 15 = 1111, 9 = 1001 */ assert(1 == invert(5, 2, 1)); /* 5 = 101 */ return 0; }