include/libtorrent/bitfield.hpp
// count the number of bits in the bitfield that are set to 1.
count the number of bits in the bitfield that are set to 1.
count the number of bits in the bitfield that are set to 1 .
int count() const
		{
			int ret = 0;
			const int words = num_words();
#if TORRENT_HAS_SSE
			unsigned int cpui[4];
			cpuid(cpui, 1);
			if (cpui[2] & (1 << 23))
			{
				for (int i = 0; i < words; ++i)
				{
#ifdef __GNUC__
					ret += __builtin_popcount(m_buf[i]);
#else
					ret += _mm_popcnt_u32(m_buf[i]);
#endif
				}
				return ret;
			}	
#endif 
			for (int i = 0; i < words; ++i)
			{
				boost::uint32_t v = m_buf[i];
				static const int S[] = {1, 2, 4, 8, 16}; 
				static const int B[] = {0x55555555, 0x33333333, 0x0F0F0F0F, 0x00FF00FF, 0x0000FFFF};
				boost::uint32_t c = v - ((v >> 1) & B[0]);
				c = ((c >> S[1]) & B[1]) + (c & B[1]);
				c = ((c >> S[2]) + c) & B[2];
				c = ((c >> S[3]) + c) & B[3];
				c = ((c >> S[4]) + c) & B[4];
				ret += c;
			}
			TORRENT_ASSERT(ret <= size());
			TORRENT_ASSERT(ret >= 0);
			return ret;
		}
int count ( ) const { int ret = 0 ; const int words = num_words ( ) ; #if TORRENT_HAS_SSE unsigned int cpui [ 4 ] ; cpuid ( cpui , 1 ) ; if ( cpui [ 2 ] & ( 1 << 23 ) ) { for ( int i = 0 ; i < words ; ++ i ) { #ifdef __GNUC__ ret += __builtin_popcount ( m_buf [ i ] ) ; #else ret += _mm_popcnt_u32 ( m_buf [ i ] ) ; #endif } return ret ; } #endif for ( int i = 0 ; i < words ; ++ i ) { boost :: uint32_t v = m_buf [ i ] ; static const int S [ ] = { 1 , 2 , 4 , 8 , 16 } ; static const int B [ ] = { 0x55555555 , 0x33333333 , 0x0F0F0F0F , 0x00FF00FF , 0x0000FFFF } ; boost :: uint32_t c = v - ( ( v >> 1 ) & B [ 0 ] ) ; c = ( ( c >> S [ 1 ] ) & B [ 1 ] ) + ( c & B [ 1 ] ) ; c = ( ( c >> S [ 2 ] ) + c ) & B [ 2 ] ; c = ( ( c >> S [ 3 ] ) + c ) & B [ 3 ] ; c = ( ( c >> S [ 4 ] ) + c ) & B [ 4 ] ; ret += c ; } TORRENT_ASSERT ( ret <= size ( ) ) ; TORRENT_ASSERT ( ret >= 0 ) ; return ret ; }
count the number of bits in the bitfield that are set to 1.
count the number of bits in the bitfield that are set to 1 .
// TORRENT_HAS_SSE // from: // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel // Magic Binary Numbers