Domanda

So, I have a more complex question to solve overall, but currently I'm unable to add two numbers. I know about the 'add' command. It works great when you're just adding an integer to an register-assigned value. When it comes to adding two numbers from the memory, they're initially strings, which requires converting to integers before (that's my guess). Any help?

SECTION .data
    msg1    db  'Enter 2 numbers:', 0Ah
    msg2    db  'You entered:', 0Ah
    msg3    db  'Sum: '

SECTION .bss
one:    resb    4
two:    resb    4
sum:    resb    4


SECTION .text
global _start

_start:

mov eax, 4
mov ebx, 1
mov ecx, msg1
mov edx, 32
int 80h

mov eax, 3
mov ebx, 0
mov ecx, one
mov edx, 4
int 80h

mov eax, 3  
mov ebx, 0
mov ecx, two
mov edx, 4
int 80h

mov eax, 4
mov ebx, 1
mov ecx, msg2
mov edx, 39
int 80h

mov eax, 4
mov ebx, 1
mov ecx, one
mov edx, 4
int 80h

mov eax, 4
mov ebx, 1
mov ecx, two
mov edx, 4
int 80h

mov eax, 4
mov ebx, 1
mov ecx, sum
mov edx, 4
int 80h

mov eax, 1
mov ebx, 0
int 80h
È stato utile?

Soluzione

By my understanding of your question, you are reading two strings which represent numbers, and you want to add those numbers.

You are right by saying that initially, you don't have numbers, but strings. If you want to add the numbers that the string represent, you should first find a way of converting the strings to the usual numeric representation that you work with.

There are a few possibilities. You may use a library function, for example strtol (You should like to that library). You should call this function with the string as an argument, and it will do the job for you. You will get the result in side the eax register.

If you want to achieve some larger educational value, you might want to calculate the number yourself. It is not that hard, and I really recommend to do it at least once in a lifetime.

First there is the base question. You probably assume that the number you have received is in base 10. You will also want to convert every ascii digit into its value. In that case, you may just subtract 0x30, or '0'.

If the number that you got is a_0,a_1,a_2,a_3 for example (After subtracting the 0x30), then you have to calculate it as 1*a_0 + 10*a_1 + 100*a_2 + 1000*a_3. Create a loop that does just that. The result that you get is the actual number.

Note though, that you will probably have to do the opposite base translation when you want to print the number back to the console. For the other case, you should repeatedly divide and use modulo 10 to get the digits in base 10. Finally you should add 0x30 to all the base 10 digits, and print those characters.

Good luck :)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top