Counting the number of bits that are set

csguy11 picture csguy11 · Sep 22, 2010 · Viewed 8.4k times · Source

I want to count the number of bits in a binary number that are set. For example, user enter the number 97 which is 01100001 in binary. The program should give me that 3 bits are set using MIPS ISA.

I am able to achieve this in C, but I don't know how to achieve it using assembly code.

Answer

Chris Schmich picture Chris Schmich · Sep 22, 2010

What you're looking for is often referred to as the population count (popcount).

There are a number of C implementations on Bit Twiddling Hacks (some of which are scarily clever). If you're familiar with C, each approach should have a reasonable translation into MIPS assembly after breaking down the expressions.

If your input domain is small (e.g. 0-255), you could always do a lookup table and use the input as the offset to fetch the popcount directly.