bit_util.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <climits>
  6. #include <cstddef>
  7. #include "common/common_types.h"
  8. namespace Common {
  9. /// Gets the size of a specified type T in bits.
  10. template <typename T>
  11. [[nodiscard]] constexpr std::size_t BitSize() {
  12. return sizeof(T) * CHAR_BIT;
  13. }
  14. [[nodiscard]] constexpr u32 MostSignificantBit32(const u32 value) {
  15. return 31U - static_cast<u32>(std::countl_zero(value));
  16. }
  17. [[nodiscard]] constexpr u32 MostSignificantBit64(const u64 value) {
  18. return 63U - static_cast<u32>(std::countl_zero(value));
  19. }
  20. [[nodiscard]] constexpr u32 Log2Floor32(const u32 value) {
  21. return MostSignificantBit32(value);
  22. }
  23. [[nodiscard]] constexpr u32 Log2Floor64(const u64 value) {
  24. return MostSignificantBit64(value);
  25. }
  26. [[nodiscard]] constexpr u32 Log2Ceil32(const u32 value) {
  27. const u32 log2_f = Log2Floor32(value);
  28. return log2_f + static_cast<u32>((value ^ (1U << log2_f)) != 0U);
  29. }
  30. [[nodiscard]] constexpr u32 Log2Ceil64(const u64 value) {
  31. const u64 log2_f = Log2Floor64(value);
  32. return static_cast<u32>(log2_f + static_cast<u64>((value ^ (1ULL << log2_f)) != 0ULL));
  33. }
  34. } // namespace Common