Counting the number of bits that are set

后端 未结 3 717
悲&欢浪女
悲&欢浪女 2021-01-21 09:23

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

3条回答
  •  孤街浪徒
    2021-01-21 10:06

    Since this sounds like homework, I'm not going to give the MIPS code, but here's the algorithm (written in C). It should be straightforward to translate into MIPS:

    int bits(unsigned int number)
    {
        // clear the accumulator
        int accumulator = 0;
        // loop until our number is reduced to 0
        while (number != 0)
        {
            // add the LSB (rightmost bit) to our accumulator
            accumulator += number & 1;
            // shift the number one bit to the right so that a new
            // bit is in the LSB slot
            number >>= 1;
        }
        return accumulator;
    }
    

提交回复
热议问题