bit_util.h 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 <bit>
  6. #include <climits>
  7. #include <cstddef>
  8. #include "common/common_types.h"
  9. namespace Common {
  10. /// Gets the size of a specified type T in bits.
  11. template <typename T>
  12. [[nodiscard]] constexpr std::size_t BitSize() {
  13. return sizeof(T) * CHAR_BIT;
  14. }
  15. [[nodiscard]] constexpr u32 MostSignificantBit32(const u32 value) {
  16. return 31U - static_cast<u32>(std::countl_zero(value));
  17. }
  18. [[nodiscard]] constexpr u32 MostSignificantBit64(const u64 value) {
  19. return 63U - static_cast<u32>(std::countl_zero(value));
  20. }
  21. [[nodiscard]] constexpr u32 Log2Floor32(const u32 value) {
  22. return MostSignificantBit32(value);
  23. }
  24. [[nodiscard]] constexpr u32 Log2Floor64(const u64 value) {
  25. return MostSignificantBit64(value);
  26. }
  27. [[nodiscard]] constexpr u32 Log2Ceil32(const u32 value) {
  28. const u32 log2_f = Log2Floor32(value);
  29. return log2_f + static_cast<u32>((value ^ (1U << log2_f)) != 0U);
  30. }
  31. [[nodiscard]] constexpr u32 Log2Ceil64(const u64 value) {
  32. const u64 log2_f = Log2Floor64(value);
  33. return static_cast<u32>(log2_f + static_cast<u64>((value ^ (1ULL << log2_f)) != 0ULL));
  34. }
  35. } // namespace Common