Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 30, 2009 08:15
Show Gist options
  • Save shaobin0604/222216 to your computer and use it in GitHub Desktop.
Save shaobin0604/222216 to your computer and use it in GitHub Desktop.
/*
* 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.
*/
#include <stdio.h>
unsigned int setbits(unsigned int x, int p, int n, unsigned int y);
unsigned int setbits(unsigned int x, int p, int n, unsigned int y) {
return (x & ~(((1 << n) - 1) << (p + 1 - n))) | ((y & ~(~0 << n)) << (p + 1 - n));
}
int main(void) {
unsigned int x = 0x48;
unsigned int y = 0x91;
unsigned int r = 0x44;
int p = 4;
int n = 3;
if (r == setbits(x, p, n, y))
printf("assert success!\n");
else
printf("assert fail!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment