0

I found an algorithm for population count which goes like this:

unsigned int v; // count the number of bits set in v
unsigned int c; // c accumulates the total bits set in v
for (c = 0; v; c++)
{
  v &= v - 1; // clear the least significant bit set
}

My question is, is it possible to implement this into Assembly (MIPS) ? I don't understand how the "for" loop works, if anyone could explain what the condition is (I suspect it's 0 < v ?). There is another question about this algorithm but it does not explain the algorithm on an instruction-level depth.

Cast some light on population count algorithm

Sidenote: My hw is to implement a popcount algorithm which counts the set bits of a 32bit interger on MIPS (a subroutine) but I am not allowed to use multiplication/division by any means. Hope my question is not a duplicate spam :/

Community
  • 1
  • 1
  • 2
    The condition here is "`v` is truthy", or in other words, `v != 0`. (This is, of course, equivalent to `v > 0` for unsigned integers.) – Frxstrem Mar 15 '17 at 20:55
  • Thank you, I wanted to make sure I understood this correctly ^^ – Alex Tsalikis Mar 15 '17 at 21:06
  • "s it possible to implement this into Assembly (MIPS)" ... guess what will happen if you compile that C with MIPS C compiler... ....ok, I will tell you, as I can feel the tension: it will implement it in MIPS assembly. – Ped7g Mar 16 '17 at 18:18
  • @Ped7g The point is for me to actually write code (and hopefully learn something from that), not generate it from a tool, copy paste it and get an artificial grade :/ But I'll have you know I wrote the code myself and it works ^_^ Thanks for the info though. – Alex Tsalikis Mar 17 '17 at 14:00
  • @AlexTsalikis sure, I appreciated you managed to do it and I hope you will enjoy the learning experience, I was just answering your (rhetorical?) question, whether it is possible. Obviously, if you can write it in C (or any other programming language supported by MIPS), it *must* be possible also in ASM. Whether it would be easy to do... with complex languages and examples very likely not. Actually writing it in C first (+debug and fix algorithm) may help with the assembly code logic and structure a lot. – Ped7g Mar 17 '17 at 14:57

0 Answers0