lolamontes69

K+R Exercise2_6

Sep 7th, 2014
237
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.28 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. unsigned getbits(unsigned x, int n, int p, unsigned y);
  4.  
  5. int main()
  6. {
  7.     unsigned x, y, res;
  8.     int p, n;
  9.  
  10.     printf("Enter x > ");
  11.     scanf("%u",&x);
  12.     printf("Enter y > ");
  13.     scanf("%u",&y);
  14.     printf("Enter n > ");
  15.     scanf("%d",&n);
  16.     printf("Enter p > ");
  17.     scanf("%d",&p);
  18.  
  19.     res = getbits(x,n,p,y);
  20.     printf("\nHere's the answer > %u\n",res);
  21.  
  22.     return(0);
  23. }
  24. /* find two parts of x and insert one part of y */
  25. unsigned getbits(unsigned x, int n, int p, unsigned y)
  26. {
  27.     unsigned rmby;    // rightmost n bits of y << p
  28.     unsigned lmbx;    // leftmost bits of x before p
  29.     unsigned rmbx;    // rightmost bits of x, n bits after p
  30.  
  31.     lmbx = (x >> p+1);       // wipe off p to 0
  32.     lmbx = (lmbx << p+1);    // returns num b4 p
  33.  
  34.     rmbx = (x-lmbx) >> p-n+1;                  // get rightmost bits of x after pn
  35.     rmbx = (x-lmbx)^(rmbx<<p-n+1);             // first removing leftmost bits
  36.    
  37.     rmby = y >> n;           // wipe off rightmost n bits
  38.     rmby = y^(rmby<<n);      // this gets rightmost n bits by comparing rmby
  39.                              // with rmby - rightmost n bits
  40.     rmby = rmby << (p-n+1);  // this leftshifts them to position p
  41.  
  42.     return (lmbx+rmbx+rmby); // Put them together.
  43. }
Advertisement
Add Comment
Please, Sign In to add comment