lolamontes69

K+R Exercise2_7

Sep 5th, 2014
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.01 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. unsigned invert(unsigned x, int p, int n);
  4.  
  5. int main()
  6. {
  7.     unsigned x, res;
  8.     int p, n;
  9.  
  10.     printf("Enter x > ");
  11.     scanf("%u",&x);                // scanf allows for overflow by using chars
  12.     printf("Enter p > ");
  13.     scanf("%d",&p);
  14.     printf("Enter n > ");
  15.     scanf("%d",&n);
  16.     res = invert(x,p,n);
  17.     printf("\nHere's the result %u\n",res);
  18.     return(0);
  19. }
  20. /* Invert n bits from position p and leave the rest of x unchanged */
  21. unsigned invert(unsigned x, int p, int n)
  22. {
  23.     unsigned lmbx, j, k, rmbx;
  24.  
  25.     lmbx = (x >> p+1) << p+1;             // get the leftmost bits before p
  26.  
  27.     rmbx = (x-lmbx) >> p-n+1;             // get rightmost bits of x after pn
  28.     rmbx = (x-lmbx)^(rmbx<<p-n+1);    
  29.  
  30.     x = ((x-lmbx) >> (p-n+1)) << (p-n+1); // so only gets pn
  31.     j = (255 >> (7-n+1)) << (p-n+1);      // get 1's at pn
  32.     k = ~((~j)+x);                        // pn inverted
  33.  
  34.     return (k+rmbx+lmbx);                 // Add back the bits from either side of pn
  35. }
Advertisement
Add Comment
Please, Sign In to add comment