Skip to content
Advertisement

How to add 2 numbers together that are of different lengths in x86 linux nasm assembly

I’m very new to assembly and having difficulties in getting basic calculations to work with different length numbers.

So this is my adding code, that works with numbers that are 3 or less characters long. for as long as both are the same length. for example 123 + 123 works just fine and outputs 246. But 12 + 123 does not work and it outputs 253 as the answer. How would I be able to get this working with different length numbers?

JavaScript

Advertisement

Answer

  • Your loop never does more than 3 iterations. If there’s a final carry, you’ll need an extra write to the destination.
  • If the code needs to deal with different length inputs, then you can’t use the same offset ESI to address corresponding digits from both numbers.
  • And neither can you use that same ESI to store the output since you could need one extra position to the left.
  • About answ resb 8, summing a couple of 3-digit numbers can at most produce a 4-digit sum.

Below is one of the many solutions to this question.

JavaScript
JavaScript

In the result in answ we can remove at most 3 leading zeroes. If the true result is 0, the 4th character in answ would have to remain.

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement