본문 바로가기
Algorithms/simulation

Hamming Weight 2

by OKOK 2021. 4. 13.

- 연산자의 숫자를 줄임

- 필요한 부분만 연산해서 나감

- 마지막에 0x7f 로 하여 필요한 비트만 추출함

 

#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_b(int x)
{
	x -= (x >> 1) & m1;
	x = (x & m2) + ((x >> 2) & m2);
	x = (x + (x >> 4)) & m4;
	x += x >> 8;
	x += x >> 16;
	return x & 0x7f;
}

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

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

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

Hamming Weight 4  (0) 2021.04.13
Hamming Weight 3  (0) 2021.04.13
Hamming Weight 1  (0) 2021.04.13
find first set / find next bit  (0) 2021.04.13
테트리스  (0) 2020.01.10

댓글