Skip to content

Instantly share code, notes, and snippets.

@cynx
Created June 11, 2014 10:27
Show Gist options
  • Save cynx/8560762a281490f94604 to your computer and use it in GitHub Desktop.
Save cynx/8560762a281490f94604 to your computer and use it in GitHub Desktop.
C program 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 setbits(unsigned x, int p, int n, unsigned y);
int main()
{
printf("%d", setbits(17, 4, 3, 13));
return 0;
}
unsigned setbits(unsigned x, int p, int n, unsigned y)
{
return(((y & ~(~0 << n)) << (p + 1 - n)) | (x & ~((~(~0 << n) << (p + 1 - n)))));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment