c - 汇编语言前缀和问题

标签 c assembly prefix-sum

所以我的任务是编写汇编代码,对一组数字执行前缀和。

给出的例子是2 4 6 -1,返回需要是12 10 6-1 用作塞子。

        jmp main
        prefix:     addl %edx, %eax
        ret


        print:      irmovl $32, %ecx
                    wrint %eax
                    wrch %ecx
                    ret


        read:       pushl %ebp           # ON_ENTRY saving old frame ptr 
                    rrmovl %esp, %ebp    # ON_ENTRY set new frame ptr

                    mrmovl 8(%ebp), %edx # Retrieving parameter
                    irmovl $1, %ecx  # writing ecx with 1
                    addl %ecx, %esi
                    addl %edx, %ecx      # adding edx and ecx
                    je baseCase          # checking if they equal 0

        recStep:    rdint %ebx       # reading parameter from user
                    pushl %ebx
                    call read
                    popl %ebx

                    mrmovl 8(%ebp), %edx

                    pushl %edx
                    call prefix
                    popl %edx


                    call print
                    jmp end
        baseCase:   irmovl $0, %eax

        end:        rrmovl %ebp, %esp # ON_EXIT reset stack ptr 
                    popl %ebp   # ON_EXIT restore old base/frame ptr 
                    ret     # ON_EXIT 

        main:       irmovl $0x1000, %esp    # init stack ptr 
                    irmovl $-1, %esi
                    rdint %ebx      # reading parameter from user

                    pushl %ebx  # pushing parameter
                    call read   # function call 
                    popl %ebx       # removing parameter


                    call prtnl 
                    halt



        prtnl:     irmovl $10, %edx  # assuming edx is caller save 
                   wrch %edx 
                   ret  

所以基本上我的代码打印 6 10 12 并且我需要找到一种方法来反转此输出。有什么想法吗?

最佳答案

So basically my code prints 6 10 12 and I need to find a way to reverse this output. Any ideas?

是的,不要使用递归——没有必要过度滥用堆栈。

取而代之的是,将每个输入都保存到堆栈中。之后将其视为一个数组——遍历每个项目并计算它的前缀和。我要做的是使用一个寄存器来指示第一项在堆栈中的起始位置,并使用 esp 和它之间的差异来获取数组长度。当收到输入时,我还会使用另一个寄存器来累加总和。

可以通过从当前 array[i] 中减去累加器并将结果存储回下一个元素的累加器来计算每个元素的前缀和。

关于c - 汇编语言前缀和问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802715/

相关文章:

c++ - 序列化和反序列化 uint64_t - 不同平台上的不同结果

c - 与堆栈指针

c - 如何在 c 中使用 64 位内联汇编?

assembly - 矮人 Hello World 汇编示例或教程?

c - Visual Studio 2013 C/C++ 调试器,让你调用一个函数并打印结果

c++ - AVX2 的汇编错误

c++ - 扫描快速排序拆分

haskell - 数据并行 Haskell 前缀和

c - 使用 openMP 并行计算前缀和(c 代码)

c - C语言读/写文件