Counting 1's in an integer using mips assembly language (without any flow of control instructions)

折月煮酒 提交于 2019-12-23 20:09:58

问题


I am currently working on a program that counts the number of 1's in an integer's binary representation, where the integer is entered by the user. I need to do it so that the program runs from top down, so that means no loops or flow of instruction of any kind. However, I am very new to Mips and assembly language, and am currently struggling with how to do this.

I think that you can use the srlv and/or sllv instructions for this with some multiplication, but I have no clue even where to start.


回答1:


The function you are describing is called the Hamming Weight.

I took a couple seconds and looked at the Wikipedia article here which contains several C algorithms for computing Hamming Weight. I chose this one (changed slightly for 32 bits and moved constants to function):

//This uses fewer arithmetic operations than any other known  
//implementation on machines with fast multiplication.
//It uses 12 arithmetic operations, one of which is a multiply.
int popcount_3(uint32_t x) {
    const uint32_t m1  = 0x55555555; //binary: 0101...
    const uint32_t m2  = 0x33333333; //binary: 00110011..
    const uint32_t m4  = 0x0f0f0f0f; //binary:  4 zeros,  4 ones ...
    const uint32_t h01 = 0x01010101; //the sum of 256 to the power of 0,1,2,3...

    x -= (x >> 1) & m1;             //put count of each 2 bits into those 2 bits
    x = (x & m2) + ((x >> 2) & m2); //put count of each 4 bits into those 4 bits 
    x = (x + (x >> 4)) & m4;        //put count of each 8 bits into those 8 bits 
    return (x * h01)>>24;  //returns left 8 bits of x + (x<<8) + (x<<16) + (x<<24) + ... 
}

In MIPS assembly this looks like:

main:

    #read in int x for Hamming Weight
    addi $v0 $zero 5
    syscall

    lui $t5 0x0101 #$t5 is 0x01010101
    ori $t5 0x0101
    lui $t6 0x5555 #$t6 is 0x55555555
    ori $t6 0x5555
    lui $t7 0x3333 #$t7 is 0x33333333
    ori $t7 0x3333
    lui $t8 0x0f0f #$t8 is 0x0f0f0f0f
    ori $t8 0x0f0f

    # x -= (x>>1) & 0x55555555
    srl $t0 $v0 1
    and $t0 $t0 $t6
    sub $v0 $v0 $t0

    # x = (x & 0x33333333) + ((x >> 2) & 0x33333333)
    and $t0 $v0 $t7
    srl $t1 $v0 2
    and $t1 $t1 $t7
    add $v0 $t0 $t1

    # x = (x + (x >> 4)) & 0x33333333
    srl $t0 $v0 4
    add $t0 $v0 $t0
    and $v0 $t0 $t8

    # output (x * 0x01010101) >> 24
    mul $v0 $v0 $t5
    srl $a0 $v0 24
    li $v0 1
    syscall

    jr $ra


来源:https://stackoverflow.com/questions/21959118/counting-1s-in-an-integer-using-mips-assembly-language-without-any-flow-of-con

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!