SDL_bits.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2013 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. /**
  19. * \file SDL_bits.h
  20. *
  21. * Functions for fiddling with bits and bitmasks.
  22. */
  23. #ifndef _SDL_bits_h
  24. #define _SDL_bits_h
  25. #include "SDL_stdinc.h"
  26. #include "begin_code.h"
  27. /* Set up for C function definitions, even when using C++ */
  28. #ifdef __cplusplus
  29. extern "C" {
  30. #endif
  31. /**
  32. * \file SDL_bits.h
  33. */
  34. /**
  35. * Get the index of the most significant bit. Result is undefined when called
  36. * with 0. This operation can also be stated as "count leading zeroes" and
  37. * "log base 2".
  38. *
  39. * \return Index of the most significant bit.
  40. */
  41. SDL_FORCE_INLINE Sint8
  42. SDL_MostSignificantBitIndex32(Uint32 x)
  43. {
  44. #if defined(__GNUC__) && __GNUC__ >= 4
  45. /* Count Leading Zeroes builtin in GCC.
  46. * http://gcc.gnu.org/onlinedocs/gcc-4.3.4/gcc/Other-Builtins.html
  47. */
  48. return 31 - __builtin_clz(x);
  49. #else
  50. /* Based off of Bit Twiddling Hacks by Sean Eron Anderson
  51. * <seander@cs.stanford.edu>, released in the public domain.
  52. * http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog
  53. */
  54. const Uint32 b[] = {0x2, 0xC, 0xF0, 0xFF00, 0xFFFF0000};
  55. const Uint8 S[] = {1, 2, 4, 8, 16};
  56. Uint8 msbIndex = 0;
  57. int i;
  58. for (i = 4; i >= 0; i--)
  59. {
  60. if (x & b[i])
  61. {
  62. x >>= S[i];
  63. msbIndex |= S[i];
  64. }
  65. }
  66. return msbIndex;
  67. #endif
  68. }
  69. /* Ends C function definitions when using C++ */
  70. #ifdef __cplusplus
  71. }
  72. #endif
  73. #include "close_code.h"
  74. #endif /* _SDL_bits_h */
  75. /* vi: set ts=4 sw=4 expandtab: */