AlfonZ
AlfonZ

Reputation: 11

Negative result on the stack in assembly

Assembly AT&T.

Hi, I have a problem when I try to do a subl.

In particular I'm trying to do x - y where x < y. But the correct result isn't put on the stack.

Here a piece of code:

....
call read             # Function to read a number (i.e. 5)
movl %eax, -8(%ebp)   # Copy the number read into the stack.
....
call read             # Function to read a number (i.e. 15)
movl %eax, -28(%ebp)  # Copy the number read into the stack.
....
movl -8(%ebp), %eax   # Copy the number 5 in EAX.
subl -28(%ebp), %eax  # EAX = 5 - 15
movl %eax, -32(%ebp)  # Put the result in -32(%ebp)
....

If I print -32(%ebp) I don't get -10 (5-15), but I get a strange symbol.

So, the question is: how can I store a negative number on the stack without change its form?

Thank you so much.

AlfonZ

Upvotes: 1

Views: 141

Answers (1)

JSF
JSF

Reputation: 5321

The bug is that your print function was not designed to support negative numbers.

You can store a negative number on the stack (or elsewhere) without changing its form. But you need whatever uses that stored value to understand that it is a signed quantity.

Your print function treats any value less than 10 as if it were a single non negative digit (by adding '0' to it and printing that single character). When you add '0' to a negative number and print that character, you get the "strange symbol" you observed.

Upvotes: 2

Related Questions