Skip to content

Instantly share code, notes, and snippets.

@tomcha
Created April 18, 2015 11:10
Show Gist options
  • Select an option

  • Save tomcha/dd03e153b72a9fd379a7 to your computer and use it in GitHub Desktop.

Select an option

Save tomcha/dd03e153b72a9fd379a7 to your computer and use it in GitHub Desktop.
2-6
#include <stdio.h>
int unsigned setbits(unsigned x, int p, int n, unsigned y);
int main(){
int x = 0b001110;
int y = 0b0000000;
int val = setbits(x, 3, 3, y);
printf("%d\n", val);
// answer 0b0000111 -> 7;
}
int unsigned setbits(unsigned x, int p, int n, unsigned y){
y = (y & ~(~0 << n)) + ((x >> (p - (n - 1))) & ~(~0 << n));
return y;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment