@@ 0,0 1,31 @@
+#include <stdio.h>
+
+/* setbits: return x with the n bits that begin at position p set to the
+ * rightmost n bits of y */
+unsigned
+setbits(unsigned x, int p, int n, unsigned y)
+{
+ /* get the rigtmost n bits of y */
+ y = y & ~(~0 << n);
+ /* place them in the position to be inserted */
+ y = y << (p - n + 1);
+ /* set those bits in x to zero */
+ x = x & ~((~(~0 << n) << (p - n + 1)));
+ /* insert those bits in x */
+ x = x | y;
+
+ return x;
+}
+
+/* check some examples */
+int
+main()
+{
+ printf("This should give 11: %d\n", setbits(15, 2, 2, 9));
+ /* 15 = 1111, 9 = 1001, 11 = 1011 */
+
+ printf("This should give 7: %d\n", setbits(5, 2, 3, 15));
+ /* 5 = 101, 15 = 1111, 7 = 111 */
+
+ return 0;
+}