General Purpose library for Freestanding C++ and POSIX systems
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
1.6 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. #pragma once
  2. #include "gp/math/details/math_definitions.hpp"
  3. #include <stdint.h>
  4. #include <stddef.h>
  5. namespace gp {
  6. namespace math {
  7. /**
  8. Sean Eron Anderson
  9. seander@cs.stanford.edu
  10. **/
  11. template<>
  12. constexpr uint32_t log2<uint32_t>(uint32_t v)
  13. {
  14. constexpr int MultiplyDeBruijnBitPosition[32] =
  15. {
  16. 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30,
  17. 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31
  18. };
  19. v |= v >> 1;
  20. v |= v >> 2;
  21. v |= v >> 4;
  22. v |= v >> 8;
  23. v |= v >> 16;
  24. return MultiplyDeBruijnBitPosition[(uint32_t)(v * 0x07C4ACDDU) >> 27];
  25. }
  26. template<>
  27. constexpr uint64_t log2<uint64_t>(uint64_t v)
  28. {
  29. constexpr int MultiplyDeBruijnBitPosition[64] =
  30. {
  31. 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61,
  32. 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62,
  33. 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56,
  34. 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5, 63
  35. };
  36. v |= v >> 1;
  37. v |= v >> 2;
  38. v |= v >> 4;
  39. v |= v >> 8;
  40. v |= v >> 16;
  41. v |= v >> 32;
  42. return MultiplyDeBruijnBitPosition[(uint64_t)(v * 0x03f6eaf2cd271461ULL) >> 58];
  43. }
  44. static_assert(log2<uint32_t>(7) == 2, "bad log2");
  45. static_assert(log2<uint32_t>(8) == 3, "bad log2");
  46. template<>
  47. constexpr uint32_t msb<uint32_t>(uint32_t v)
  48. {
  49. auto l = log2(v);
  50. return l + (((1 << l) ^ v) != 0);
  51. }
  52. template<>
  53. constexpr uint64_t msb<uint64_t>(uint64_t v)
  54. {
  55. auto l = log2(v);
  56. return l + (((1 << l) ^ v) != 0);
  57. }
  58. static_assert(msb<uint32_t>(7) == 3, "bad msb");
  59. static_assert(msb<uint32_t>(8) == 3, "bad msb");
  60. }
  61. }