Skip to content

Instantly share code, notes, and snippets.

@rickymanning

rickymanning/setbits-pt1.c Secret

Last active Jun 7, 2016
Embed
What would you like to do?
Solving exercise 2-6 setbits() from K&R (The C Programming Language, 2nd Edition) part 1
/* 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, page 49 */
#include
unsigned setbits(unsigned x, int p, int n, unsigned y);
unsigned getbits(unsigned x, int p, int n);
int main()
{
printf("%u\n", setbits(209, 4, 3, 187));
}
/* getbits: get n bits from position p */
unsigned getbits(unsigned x, int p, int n)
{
return (x >> (p+1-n)) & ~(~0 << n);
}
/* setbits: replace bits p -> p+n of x with rightmost n bits from y */
unsigned setbits(unsigned x, int p, int n, unsigned y)
{
int bits, result;
bits = getbits(y, n-1, n);
/* result = ; */
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment