I am trying to figure out how to get the number of items in the stack by subtracting the sp register with bp. What am I doing wrong? I get totally wrong result
MOV bp, 0x7E00
MOV sp, bp
PUSH 'A'
PUSH 'B'
PUSH 'C'
POP bx
MOV al, bl
CALL _printchar
POP bx
MOV al, bl
CALL _printchar
MOV bx, sp
SUB bx, bp
ADD bx, 48 ;To get ascii number
MOV al, bl
CALL _printchar
This is the output:
CB.
A really confusing thing about the stack is that it grows down.
Compared to most people's mental image of a stack, the stack you work with in assembly is "upside down". The "bottom" of the stack has the highest memory address, and the "top" has the lowest. When you push 2 bytes onto the stack, 2 bytes are subtracted from the stack pointer, not added to it. (If you think about it in terms of memory partitioning, this is actually safer)
So the result of your SUB was -2, which is '.' in ascii. You can't just switch the operands around, because the result needs to go into the first operand, so it should be a general purpose register. Instead, alter the MOV operations before the SUB.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With