1// Test for boost/core/bit.hpp (popcount)
2//
3// Copyright 2020 Peter Dimov
4// Distributed under the Boost Software License, Version 1.0.
5// https://www.boost.org/LICENSE_1_0.txt
6
7#include <boost/core/bit.hpp>
8#include <boost/core/lightweight_test.hpp>
9#include <boost/core/detail/splitmix64.hpp>
10#include <boost/cstdint.hpp>
11#include <limits>
12#include <iostream>
13
14template<class T> void test_popcount( T x )
15{
16 int k = 0;
17 for( T y = x; y; y = static_cast<T>( y & (y - 1) ), ++k );
18
19 BOOST_TEST_EQ( boost::core::popcount( x ), k ) || ( std::cerr << "x: " << +x << std::endl );
20}
21
22int main()
23{
24 {
25 test_popcount( x: static_cast<unsigned char>( 0 ) );
26 test_popcount( x: static_cast<unsigned short>( 0 ) );
27 test_popcount( x: static_cast<unsigned int>( 0 ) );
28 test_popcount( x: static_cast<unsigned long>( 0 ) );
29 test_popcount( x: static_cast<boost::ulong_long_type>( 0 ) );
30 }
31
32 boost::detail::splitmix64 rng;
33
34 for( int i = 0; i < 1000; ++i )
35 {
36 boost::uint64_t x = rng();
37
38 test_popcount( x: static_cast<unsigned char>( x ) );
39 test_popcount( x: static_cast<unsigned short>( x ) );
40 test_popcount( x: static_cast<unsigned int>( x ) );
41 test_popcount( x: static_cast<unsigned long>( x ) );
42 test_popcount( x: static_cast<boost::ulong_long_type>( x ) );
43 }
44
45 return boost::report_errors();
46}
47

source code of boost/libs/core/test/bit_popcount_test.cpp