Blogger Widgets

Search This Blog

Saturday, 28 July 2012

Some tricky programs from KNR

Qn : 1 --   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.
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 =    10110101
and y =    10111010

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

then we want to replace  x =    10110101 the underlined bits to the last three bits of y.


ie the result must be x =    10101001



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 =    10110101
       y =    10111010
      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 =    10100001
similarly
((y & ~(~0 << n)) << (p+1-n)) will give y =    00000010

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

this will give the result

  x =    10101001


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

Blogger Widgets