log2comp.h 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*! \file
  2. * \brief log2comp.h - various base 2 log computation versions
  3. *
  4. * Asterisk -- An open source telephony toolkit.
  5. *
  6. * \author Alex Volkov <codepro@usa.net>
  7. *
  8. * Copyright (c) 2004 - 2005, Digium Inc.
  9. *
  10. * This program is free software, distributed under the terms of
  11. * the GNU General Public License
  12. *
  13. * Define WANT_ASM before including this file to use assembly
  14. * whenever possible
  15. */
  16. #if defined(_MSC_VER)
  17. # define inline __inline
  18. #elif defined(__GNUC__)
  19. # define inline __inline__
  20. #else
  21. # define inline
  22. #endif
  23. #if defined(WANT_ASM) && defined(_MSC_VER) && defined(_M_IX86)
  24. /* MS C Inline Asm */
  25. # pragma warning( disable : 4035 )
  26. static inline int ilog2(int val) { __asm
  27. {
  28. xor eax, eax
  29. dec eax
  30. bsr eax, val
  31. }}
  32. # pragma warning( default : 4035 )
  33. #elif defined(WANT_ASM) && defined(__GNUC__) && (defined(__i386__) || defined(i386))
  34. /* GNU Inline Asm */
  35. static inline int ilog2(int val)
  36. {
  37. int a;
  38. __asm__
  39. ("\
  40. xorl %0, %0 ;\
  41. decl %0 ;\
  42. bsrl %1, %0 ;\
  43. "
  44. : "=&r" (a)
  45. : "mr" (val)
  46. : "cc"
  47. );
  48. return a;
  49. }
  50. #elif defined(WANT_ASM) && defined(__GNUC__) && defined(__powerpc__)
  51. static inline int ilog2(int val)
  52. {
  53. int a;
  54. __asm__ ("cntlzw %0,%1"
  55. : "=r" (a)
  56. : "r" (val)
  57. );
  58. return 31-a;
  59. }
  60. #else
  61. /* no ASM for this compiler and/or platform */
  62. /* rather slow base 2 log computation
  63. * Using looped shift.
  64. */
  65. static inline int ilog2(int val)
  66. {
  67. int i;
  68. for (i = -1; val; ++i, val >>= 1)
  69. ;
  70. return (i);
  71. }
  72. #endif