counting set bits in a 32 bit number

32bit
bits
count

#1

int NumberOfSetBits32(int i) {
i = (i & 0x55555555) + ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
i = (i & 0x0F0F0F0F) + ((i >> 4) & 0x0F0F0F0F);
return (i*(0x01010101))>>24; }

Can someone explain this code ,which finds the number of set bits in a number . I am completely unable to understand it.


#2

@bhanu1993 Hi, I think following tutorial should help you. It also has other methods to count set bits in an integer.

Counting the number of set bits in an integer.

Thanks, Hope this helps

CrucifiX


#3

@Crucifix , this is the place i took it from , but unable to understand…