1 /// 2 /// @file ilog2.cpp 3 /// @brief Test ilog2(x) function. 4 /// Note that the log2(x) function from <cmath> is not 5 /// accurate enough near 2^64. 6 /// 7 /// Copyright (C) 2021 Kim Walisch, <kim.walisch@gmail.com> 8 /// 9 /// This file is distributed under the BSD License. See the COPYING 10 /// file in the top level directory. 11 /// 12 13 #include <imath.hpp> 14 15 #include <stdint.h> 16 #include <iostream> 17 #include <cmath> 18 #include <cstdlib> 19 check(bool OK)20void check(bool OK) 21 { 22 std::cout << " " << (OK ? "OK" : "ERROR") << "\n"; 23 if (!OK) 24 std::exit(1); 25 } 26 main()27int main() 28 { 29 uint64_t n; 30 uint64_t res1; 31 uint64_t res2; 32 33 for (n = 1; n < 100000; n++) 34 { 35 res1 = ilog2(n); 36 res2 = (uint64_t) std::log2(n); 37 std::cout << "ilog2(" << n << ") = " << res1; 38 check(res1 == res2); 39 } 40 41 n = (1ull << 32) - 1; 42 res1 = ilog2(n); 43 res2 = (uint64_t) std::log2(n); 44 std::cout << "ilog2(" << n << ") = " << res1; 45 check(res1 == (uint64_t) res2); 46 47 n = 1ull << 32; 48 res1 = ilog2(n); 49 res2 = (uint64_t) std::log2(n); 50 std::cout << "ilog2(" << n << ") = " << res1; 51 check(res1 == (uint64_t) res2); 52 53 n = (1ull << 63) - 1; 54 res1 = ilog2(n); 55 std::cout << "ilog2(" << n << ") = " << res1; 56 check(res1 == 62); 57 58 n = 1ull << 63; 59 res1 = ilog2(n); 60 std::cout << "ilog2(" << n << ") = " << res1; 61 check(res1 == 63); 62 63 n = 18446744073709551615ull; 64 res1 = ilog2(n); 65 std::cout << "ilog2(" << n << ") = " << res1; 66 check(res1 == 63); 67 68 std::cout << std::endl; 69 std::cout << "All tests passed successfully!" << std::endl; 70 71 return 0; 72 } 73