Explanation about the question :--

xxx...xxxa....aax..xx and

yyyyyyyy....ynnnn..n

_____________________ and the result will be

xxx...xxxn....nnx..xx

for eg:

if x = 101

**101**01

and y = 10111

**010**

and we want to find setbits(x,4,3,y)

then we want to replace x = 101

*01 the underlined bits to the last three bits of y.*

__101__ie the result must be x = 101

**01**

*010*Ans:

/****************************************************************************

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

*****************************************************************************/

unsigned setbits(unsigned x, int p, int n, unsigned y)

{

return ((x & ((~0 << (p+1)) | ~(~0 << (p+1-n)))) |

((y & ~(~0 << n)) << (p+1-n)));

}

working

take the above eg

ie: x = 101

**101**01

y = 10111

**010**

**p = 4**

**n = 3**

(~0 << (p+1)) this will set 11100000

~(~0 << (p+1-n)) this will set 00000011

so ((~0 << (p+1)) | ~(~0 << (p+1-n)))) will gives 11100011 and

(x & ((~0 << (p+1)) | ~(~0 << (p+1-n)))) will give x = 101

**000**01

similarly

((y & ~(~0 << n)) << (p+1-n)) will give y = 00000

**010**

so finally

((x & ((~0 << (p+1)) | ~(~0 << (p+1-n)))) | ((y & ~(~0 << n)) << (p+1-n)));

this will give the result

x = 101

**01**

*010*Qn :2:-Write a function invert(x,p,n) that returns x with the n bits that begin at

position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

for ans

pls check my github

https://github.com/unais/KNR/blob/master/chapter_2/2-7.c

## No comments:

## Post a Comment