Ask HN: How does 6502 stack pointer store addr 0x10FF being an 8bit register

1 points by SairajK19 ↗ HN
Hello, I was working on emulating 6502 processor, I came to know that 6502 has a 8bit SP which starts from 0x0100 to 0x01FF. So how does it store 0x01FF which is over 8 bits.

Thankyou!

9 comments

[ 4.8 ms ] story [ 31.9 ms ] thread
It does not store 01ff. It stores 00 to ff. The stack is always on page 1 (0x01..) and can not be moved elsewhere. The CPU hardware simply outputs 0x01 on the upper eight bits of the address bus while outputting the 8-bit stack pointer on the lower eight bits of the bus.
Thankyou,So this means the cpu outputs data into the upper 8bits of the address and the stack pointer points to the lower 8bits?

So for example if the current top of the stack is 0x01FF then then SP will store FF, which being upper 8 bits of 0x01FF and the data will be at 01 which being lower 8bits of 0x01FF ?

Effectively, the top eight bits of the address bus are hard wired to always be 0x01 when the "stack" is being accessed. It is part of the decode and execution hardware of the CPU.

It is also why the stack is always in page 1, and can not be moved to any other page.

The stack pointer is used to drive the lower eight bits of the address bus during a stack read or write. The upper eight bits are always 0x01.

Okay I get it now, upper 8bit always hard wired to be 0x01 which is also why lies in page 1. The stack pointer deals with lower 8bits from 00 to FF.

Many thanks!

That also restricts the stack to only 256 bytes, or 128 16-bit words.

I wonder how that affects the use of a stack-machine programming language like C. Especially when running a program like 'Towers of Hanoi'.

Wouldn't the 6502 run out of stack-space?

Yes, seems like you can easily run out of stack with 256 bytes. Maybe they used their own secondary stack along with the hardware stack.

I wonder how big is modern 64bit cpu stack.

I wonder how big is modern 64bit cpu stack.

In practical terms, I would consider it infinite. I doubt that we'd ever get to the point where we'd need even one-gigabyte of stack-space. And most modern machines have many, many gigabytes of RAM, as well as terabytes of disk storage that can be used as swap/stack/heap/cache space.

There are only 256 different values for the stack pointer. That’s low enough to fit in a 8-bit register.

See it as a digital display with two hex digits and the value “0x01” painted in front of it:

    0x0142
        ^^ two hex digits: the value in the register
    ^^^^ painted on the front plate of the display
The cpu, similarly, hard-wires those 8 bits (seven zeros and a single one) in front of the register value when accessing the stack.
That explains it well, thankyou!