如何计算十进制中某个数字的二进制的位 “1” 的数量
1 #include <iosteam>
2
3 template<class T>
4 static uint32_t CreateBytes(T value) {
5 uint32_t result = 0;
6 for (; value; ++result) {
7 value &= value - 1;
8 }
9 return result;
10 }
11
12 int main() {
13 std::cout << CreateBytes<int>(3) << std::endl;
14
15 std::cout << "Hello world" << std::endl;
16 return 0;
17 }
运行结果:
2