shaobin0604
10/30/2009 - 8:15 AM

tcpl_ex-2-6.c

/* 
 * Exercise 2-6. Write a function setbits(x,p,n,y) that returns x with the n bits
 * that begin at position p set to the rightmost n bits of y, leaving the other 
 * bits unchanged.
 */
#include <stdio.h>

unsigned int setbits(unsigned int x, int p, int n, unsigned int y);

unsigned int setbits(unsigned int x, int p, int n, unsigned int y) {
	return (x & ~(((1 << n) - 1) << (p + 1 - n))) | ((y & ~(~0 << n)) << (p + 1 - n));
}

int main(void) {
	unsigned int x = 0x48;
	unsigned int y = 0x91;
	unsigned int r = 0x44;

	int p = 4;
	int n = 3;

	if (r == setbits(x, p, n, y))
		printf("assert success!\n");
	else
		printf("assert fail!\n");
	return 0;
}