x86汇编中的总和1 + 11 + 111 ... n个项 [英] Sum 1 + 11 + 111... n terms in x86 Assembly

查看:103
本文介绍了x86汇编中的总和1 + 11 + 111 ... n个项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试给定一个数字n来求和1 + 11 + 111,该数字确定了我加在一起的序列的多少个值.即n = 2,我将添加1 + 11,或者n = 3,我将添加1 + 11 +111.我已经在C中编写了该函数,但是我试图将其转换为x86程序集,但遇到了麻烦. 这是C函数:

int summation(int n)
   {
    int sum = 0, j = 1;
    for (int i = 1; i <= n; i++)
    {
    sum = sum + j;

    // Appending a 1 at the end
    j = (j * 10) + 1;
   }

    return sum;

这是我的x86汇编代码:

unsigned int seriesSum(int n)
{
unsigned int sum=0;

__asm 
{
   mov ebx, n //input n
   mov eax, 1
   mov ecx, 10
   mov edx, 0



   Begin:
   cmp ebx, 0 // determines end of loop or not
   je EndOfWhile
       add edx, edx
       add edx, eax
       mul ecx
       add eax, eax
       inc eax
       dec ebx

       jmp Begin //Loop back

    EndOfWhile:
   mov sum, edx 


}
return sum;

我以为我的翻译正确,但是我的总和似乎是0.

解决方案

您正在使用edx来保存您的总和,但是mul ecx指令会将结果的高位单词放入edx中,以掩盖它. /p>

So I'm trying to sum 1 + 11 + 111 given a number, n, which determines how many values of the series I add together. i.e n = 2, I will add 1 + 11, or n = 3, I will add 1 + 11 + 111. I have written the function in C already, but I am trying to translate it into x86 assembly and I am having trouble. Here is the C function:

int summation(int n)
   {
    int sum = 0, j = 1;
    for (int i = 1; i <= n; i++)
    {
    sum = sum + j;

    // Appending a 1 at the end
    j = (j * 10) + 1;
   }

    return sum;

Here is my x86 assembly code:

unsigned int seriesSum(int n)
{
unsigned int sum=0;

__asm 
{
   mov ebx, n //input n
   mov eax, 1
   mov ecx, 10
   mov edx, 0



   Begin:
   cmp ebx, 0 // determines end of loop or not
   je EndOfWhile
       add edx, edx
       add edx, eax
       mul ecx
       add eax, eax
       inc eax
       dec ebx

       jmp Begin //Loop back

    EndOfWhile:
   mov sum, edx 


}
return sum;

I thought I have it translated correctly but I seem to be getting 0s as my sum.

解决方案

You're using edx to hold your sum, but the mul ecx instruction puts the upper word of the result into edx clobbering it.

这篇关于x86汇编中的总和1 + 11 + 111 ... n个项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆