home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / vc98 / crt / src / rotl.c < prev    next >
C/C++ Source or Header  |  1998-06-17  |  2KB  |  77 lines

  1. /***
  2. *rotl.c - rotate an unsigned integer left
  3. *
  4. *       Copyright (c) 1989-1997, Microsoft Corporation. All rights reserved.
  5. *
  6. *Purpose:
  7. *       defines _rotl() - performs a rotate left on an unsigned integer.
  8. *
  9. *******************************************************************************/
  10.  
  11.  
  12. #include <cruntime.h>
  13. #include <stdlib.h>
  14. #include <limits.h>
  15.  
  16. #ifdef _MSC_VER
  17. #pragma function(_lrotl,_rotl)
  18. #endif  /* _MSC_VER */
  19.  
  20. #if UINT_MAX != 0xffffffff
  21. #error This module assumes 32-bit integers
  22. #endif  /* UINT_MAX != 0xffffffff */
  23.  
  24. #if UINT_MAX != ULONG_MAX
  25. #error This module assumes sizeof(int) == sizeof(long)
  26. #endif  /* UINT_MAX != ULONG_MAX */
  27.  
  28. /***
  29. *unsigned _rotl(val, shift) - int rotate left
  30. *
  31. *Purpose:
  32. *       Performs a rotate left on an unsigned integer.
  33. *
  34. *       [Note:  The _lrotl entry is based on the assumption
  35. *       that sizeof(int) == sizeof(long).]
  36. *Entry:
  37. *       unsigned val:   value to rotate
  38. *       int    shift:   number of bits to shift by
  39. *
  40. *Exit:
  41. *       returns rotated value
  42. *
  43. *Exceptions:
  44. *       None.
  45. *
  46. *******************************************************************************/
  47.  
  48. unsigned long __cdecl _lrotl (
  49.         unsigned long val,
  50.         int shift
  51.         )
  52. {
  53.         return( (unsigned long) _rotl((unsigned) val, shift) );
  54. }
  55.  
  56. unsigned __cdecl _rotl (
  57.         unsigned val,
  58.         int shift
  59.         )
  60. {
  61.         register unsigned hibit;        /* non-zero means hi bit set */
  62.         register unsigned num = val;    /* number to rotate */
  63.  
  64.         shift &= 0x1f;                  /* modulo 32 -- this will also make
  65.                                            negative shifts work */
  66.  
  67.         while (shift--) {
  68.                 hibit = num & 0x80000000;  /* get high bit */
  69.                 num <<= 1;              /* shift left one bit */
  70.                 if (hibit)
  71.                         num |= 1;       /* set lo bit if hi bit was set */
  72.         }
  73.  
  74.         return num;
  75. }
  76.  
  77.