K&R C Exercise 2-6 Solution

/*
 * 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.
 * 
 * fduan, Dec. 13, 2011.
 */
#include <stdio.h>
#include <assert.h>

unsigned setbits( unsigned x, int p, int n, unsigned y )
{
	unsigned t;  /* unchanged lower bits */
	assert( p >= n );
	t = x & ~( ~0 << ( p - n + 1 ) );
	x >>= p + 1;
	x <<= n;
	x |= y & ~( ~0 << n );
	x <<= ( p - n + 1 );
	x |= t;
	return x;
}

int main()
{
	int x = 9, y = 10;
	int p = 2, n = 2;
	printf( "%u\n", setbits( x, p, n, y ) );
	return 0;
}

你可能感兴趣的:(K&R C Exercise 2-6 Solution)