binary.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. #include "simple/support/bits.hpp"
  2. #include <climits>
  3. using namespace simple::support;
  4. template <int n>
  5. constexpr void powers_of_two()
  6. {
  7. static_assert(count_trailing_zeros(1 << n) == n);
  8. static_assert(count_leading_zeros(1 << n) == sizeof(1) * CHAR_BIT - 1 - n);
  9. powers_of_two<n-1>();
  10. };
  11. template <>
  12. constexpr void powers_of_two<0>(){}
  13. int main()
  14. {
  15. static_assert(count_ones(0) == 0);
  16. static_assert(count_ones(-1) == sizeof(int) * CHAR_BIT);
  17. static_assert(count_ones(0b1) == 1);
  18. static_assert(count_ones(0b1010101) == 4);
  19. // TODO; these large literal tests are dubious, not a given that they won't overflow
  20. static_assert(count_ones(0x1000'0101'1010'0000LL) == 5);
  21. static_assert(count_trailing_zeros(0b1) == 0);
  22. static_assert(count_trailing_zeros(0b1000) == 3);
  23. static_assert(count_trailing_zeros(0x1000'0101'1010'0000LL) == 5*4);
  24. static_assert(count_trailing_zeros(0x0000'0101'1010'0001LL) == 0);
  25. static_assert(count_trailing_zeros(1 << 0) == 0);
  26. static_assert(count_leading_zeros(0b1) == sizeof(0b1) * CHAR_BIT - 1);
  27. static_assert(count_leading_zeros(0b1000) == sizeof(0b1000) * CHAR_BIT - 4);
  28. static_assert(count_leading_zeros(0b10101011000) == sizeof(0b1000) * CHAR_BIT - 11);
  29. static_assert(count_leading_zeros(1 << 0) == sizeof(1) * CHAR_BIT - 1);
  30. powers_of_two<sizeof(int) * CHAR_BIT - 1>();
  31. return 0;
  32. }