본문 바로가기
Algorithms/simulation

Hamming Weight 3

by OKOK 2021. 4. 13.

- version 2에서 8, 16, 0x7f 가 바뀌었음

- h01가 0x01010101; 이므로 이것을 곱한다음에 >>24를 하면 됨

 

#include <stdio.h>
const int m1  = 0x55555555; 
const int m2  = 0x33333333; 
const int m4  = 0x0f0f0f0f; 
const int m8  = 0x00ff00ff; 
const int m16 = 0x0000ffff; 
const int h01 = 0x01010101; 

int popcount_c(int x)
{
	x -= (x >> 1) & m1;             
	x = (x & m2) + ((x >> 2) & m2); 
	x = (x + (x >> 4)) & m4;        
	return (x * h01) >> 24;  
}

int __sw_hweight32(int w)
{
	w -= (w >> 1) & 0x55555555;
	w =  (w & 0x33333333) + ((w >> 2) & 0x33333333);
	w =  (w + (w >> 4)) & 0x0f0f0f0f;
	return (w * 0x01010101) >> 24;
}

int main()
{
	int bitmap = 0x12345678;
	int count;

	count = __sw_hweight32(bitmap);
	printf("count=%d\n", count );
	return 0;
}

'Algorithms > simulation' 카테고리의 다른 글

Bit Reverse  (0) 2021.04.13
Hamming Weight 4  (0) 2021.04.13
Hamming Weight 2  (0) 2021.04.13
Hamming Weight 1  (0) 2021.04.13
find first set / find next bit  (0) 2021.04.13

댓글