使用mips汇编语言在整数中计数1(没有任何控制指令流)

时间:2014-02-22 19:11:45

标签: assembly mips

我目前正在开发一个程序,它以整数的二进制表示形式计算1的数量,其中整数由用户输入。我需要这样做,以便程序从上到下运行,这意味着没有循环或任何类型的指令流。但是,我对Mips和汇编语言很陌生,目前我正在努力解决这个问题。

我认为你可以使用srlv和/或sllv指令进行一些乘法,但我不知道哪里可以开始。

1 个答案:

答案 0 :(得分:3)

您描述的功能称为汉明重量。

我花了几秒钟看了一下维基百科的文章here,其中包含几个用于计算汉明重量的C算法。我选择了这一个(稍微改为32位并将常数移动到函数):

//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) + ... 
}

在MIPS程序集中,这看起来像:

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