~josealberto4444/learning-C

298de2943727584a421d4713a41cac107b0425eb — José Alberto Orejuela García 4 years ago 986e262 master
Add exercise (2-6)

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.
1 files changed, 31 insertions(+), 0 deletions(-)

A 2-6/setbits.c
A 2-6/setbits.c => 2-6/setbits.c +31 -0
@@ 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;
}