Skip to content

Instantly share code, notes, and snippets.

@rickymanning
Last active June 7, 2016 11:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rickymanning/b67d4b576389faf257ad8ef38fd3cc81 to your computer and use it in GitHub Desktop.
Save rickymanning/b67d4b576389faf257ad8ef38fd3cc81 to your computer and use it in GitHub Desktop.
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