lolamontes69

K+R Exercise2_8

Sep 5th, 2014
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.95 KB | None | 0 0
  1. /* Write a function rightrot(x,n) that returns the value of the integer x
  2.    rotated to the right by n positions */
  3.  
  4. #include <stdio.h>
  5.  
  6. unsigned rightrot(unsigned x, int n);
  7.  
  8. int main()
  9. {
  10.     unsigned x, res;
  11.     int p, n;
  12.  
  13.     printf("Enter x > ");    // scanf probs input overflow
  14.     scanf("%u",&x);          // type in 'frog'
  15.     printf("Enter n > ");
  16.     scanf("%d",&n);
  17.     res = rightrot(x,n);
  18.     printf("\nHere's the result %u\n",res);
  19.     return(0);
  20. }
  21. /* rightrotate x and add bits snipped off to left-hand side*/
  22. unsigned rightrot(unsigned x, int n)
  23. {
  24.     int i, j;
  25.     unsigned lx, rx, rspx;                  //rspx = >> part of x
  26.     // lx,rx are left and right sides of x (rx being right n bits)
  27.  
  28.     rspx = x >> n;
  29.     lx = rspx << n;
  30.     rx = (x-lx) >> n;
  31.     rx = (x-lx)^(rx<<n);    
  32.  
  33.     i=256;
  34.     j=0;
  35.     while(x>=i) {
  36.         i = i*2;
  37.         ++j;
  38.     }
  39.     rx = rx << (8-n)+j;
  40.    
  41.     return (rx+rspx);
  42. }
Advertisement
Add Comment
Please, Sign In to add comment