Sum of 1 + 11 + 111 ... n terms in x86

So, I'm trying to summarize 1 + 11 + 111, given the number n, which determines how many series values ​​I add together. those. n = 2, I will add 1 + 11 or n = 3, I will add 1 + 11 + 111. I already wrote a function in C, but I'm trying to transfer it to the x86 assembly, and I am having problems, 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 assembler 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 translated it correctly, but it looks like I am getting 0s as my sum.

0
source share
2 answers

You use edx to store your amount, but the mul ecx command puts the top word of the result in edx , knocking it out.

+2
source

Use imul eax, ecx to just make eax *= ecx without saving anywhere. (One imul operand is a complete multiplication, which stores the result in edx:eax .)

Or even better, eax = eax*10 +1 in x86 is best done with add eax,eax / lea eax, [eax+eax*4 + 1] , and not with mul or imul at all. In fact, by optimizing latency instead of code size, you would like to avoid the 3-component LEA by dividing it by

 lea eax, [eax + eax*4] ; eax *= 5 lea eax, [1 + eax*2] ; NOT [ 1 + eax + eax ], which is shorter but slower ; eax = orig_eax*5*2 + 1 

NASM and YASM optimize this for code size in [ 1 + eax + eax*1 ] (so it can use base + scaled-index + disp8 instead of disp32 + scaled-index ). I am not sure how to override the addressing mode; [dword 1 + eax*2] uses disp32, but it still splits eax*2 into eax + eax*1 , and strict eax*2 not going to. Hopefully there is an answer to How to get NASM to encode [1 + rax * 2] as disp32 + index * 2 instead of disp8 + base + index?

Obviously, MASM will be different, but I don't have MASM.

0
source

Source: https://habr.com/ru/post/1275428/


All Articles