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

标签 assembly mips

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

我认为你可以使用 srlv和/或 sllv用一些乘法来说明这一点,但我什至不知道从哪里开始。

最佳答案

您所描述的函数称为汉明权重。

我花了几秒钟看了维基百科文章 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

关于assembly - 使用 mips 汇编语言计算整数中的 1(没有任何控制指令流),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21959118/

相关文章:

c - 如何让strcmp在汇编中返回0

macos - 程序集 - 无法设置断点 lldb

将汇编内联从 32 位转换为 64 位

c - MIPS 指令的简单 C 函数

linux - 如何确定 linux 中 cpu 的最大速度(MIPS 架构)

vhdl - 在单周期数据路径中加载半字和加载字节

c++ - MIPS 上 pthreads 中的段错误

linux - 汇编语言接受用户输入但显示输出

assembly - 在编码 VEX 指令时,NDS、NDD 和 DDS 代表什么?

assembly - MIPS lui指令的word格式如何?