Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_2.6_setbits.c
1240 views
1
/**
2
*
3
* Exercise 2.6 - Write a function setbits(x,p,n,y) that returns x with the
4
* n bits that begin at positionp set to the rightmost n bits of y,leaving
5
* the other bits unchanged.
6
**/
7
8
#include<stdio.h>
9
10
unsigned setbits(unsigned x,int p,int n,unsigned y);
11
12
int main(void)
13
{
14
printf("%u",setbits((unsigned)12,3,2,(unsigned)57));
15
}
16
17
unsigned setbits(unsigned x,int p,int n,unsigned y)
18
{
19
return x & ~(~(~0 << n) << (p+1-n)) | ( y & (~(~0<<n)) << (p+1-n));
20
}
21
22