commit 1ce4d806ce9d151bca7396796272505d06c710e3 from: jrmu date: Wed Feb 4 00:02:17 2026 UTC Add solution for 2-7 commit - e3b4721f113543c97e51e1b1b2f18e82dda160ff commit + 1ce4d806ce9d151bca7396796272505d06c710e3 blob - /dev/null blob + e922e78991e4005a5a31b4382707f077c5080639 (mode 644) --- /dev/null +++ 2-7-input @@ -0,0 +1,10 @@ +0x7de65afe 15 4 0x7de6aafe +0xadd230f1 23 6 0xad2e30f1 +0x0feb3112 31 9 0xf06b3112 +0xa0b0c118 2 2 0xa0b0c11e +0x001992ba 17 8 0x001a6eba +0xabcdef01 12 9 0xabcdf0f1 +0x12345678 27 7 0x1dd45678 +0x92fab3da 9 5 0x92fab03a +0x1ba83dea 17 11 0x1babc26a + blob - /dev/null blob + 9633d797704f5907de41f816ff2b2f97a444f360 (mode 644) --- /dev/null +++ 2-7-output @@ -0,0 +1,11 @@ +Type input line x n p expected + %x %d %d %x +result = 0x7de6aafe, expect = 0x7de6aafe +result = 0xad2e30f1, expect = 0xad2e30f1 +result = 0xf06b3112, expect = 0xf06b3112 +result = 0xa0b0c11e, expect = 0xa0b0c11e +result = 0x1a6eba, expect = 0x1a6eba +result = 0xabcdf0f1, expect = 0xabcdf0f1 +result = 0x1dd45678, expect = 0x1dd45678 +result = 0x92fab03a, expect = 0x92fab03a +result = 0x1babc26a, expect = 0x1babc26a blob - /dev/null blob + 96ab4ba2b480274348292e36ff1759dc0f6a29b5 (mode 644) --- /dev/null +++ 2-7.c @@ -0,0 +1,80 @@ +/* 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. + */ + +#include + +#define MAXLINE 1000 /* maximum input line size */ + +unsigned getbits(unsigned x, int p, int n); +unsigned setbits(unsigned x, int p, int n, unsigned y); +unsigned invert(unsigned x, int p, int n); + +int main() { + + printf("Type input line x n p expected\n"); + printf(" %%x %%d %%d %%x\n"); + unsigned x = 0; + int n = 0; + int p = 0; + unsigned result = 0; + unsigned expect = 0; + + while(scanf("%x %d %d %x\n", &x, &n, &p, &expect) == 4) { + result = invert(x, n, p); + printf("result = 0x%x, expect = 0x%x\n", result, expect); + } + return 0; +} + +/* getbits: get n bits from position p + * + * From K&R Cv2: + * getbits(x,p,n) returns the (right adjusted) n-bit field of x that begins at + * position p. We assume that bit position 0 is at the right end and that n + * and p are sensible positive values. For example, getbits(x,4,3) returns the + * three bits in bit positions 4, 3, and 2, right adjusted +*/ +unsigned getbits(unsigned x, int p, int n) { + return (x >> (p+1-n)) & ~(~0 << n); +} + +/* setbits: set n bits beginning at position p in x to rightmost n bits of y */ +unsigned setbits(unsigned x, int p, int n, unsigned y) { + return (x & ~(~(~0<