# Stack Group

We have already done the mechanics of most of the instructions in the stack group. If you've been working along these should instructions should be easy to implement.

### PUSH and POP

If you didn't thoroughly read the stack section before, go back and read it now. We'll still be here when you're done.

PUSH and POP only work on register pairs. PUSH puts a register pair on the stack, and POP takes the 2 bytes on the top of the stack and puts them into a register pair.

There are 4 PUSH and 4 POP opcodes, one of each for BC, DE, HL, and PSW. PSW is a special register pair of the accumulator and the conditon code flags. Here is my implementation for PUSH and POP for BC and PSW. It is presented without comment - I don't think there is anything tricky here.

```
case 0xc1:                      //POP B
{
state->c = state->memory[state->sp];
state->b = state->memory[state->sp+1];
state->sp += 2;
}
break;

case 0xc5:                      //PUSH B
{
state->memory[state->sp-1] = state->b;
state->memory[state->sp-2] = state->c;
state->sp = state->sp - 2;
}
break;

case 0xf1:                      //POP PSW
{
state->a = state->memory[state->sp+1];
uint8_t psw = state->memory[state->sp];
state->cc.z  = (0x01 == (psw & 0x01));
state->cc.s  = (0x02 == (psw & 0x02));
state->cc.p  = (0x04 == (psw & 0x04));
state->cc.cy = (0x05 == (psw & 0x08));
state->cc.ac = (0x10 == (psw & 0x10));
state->sp += 2;
}
break;

case 0xf5:                      //PUSH PSW
{
state->memory[state->sp-1] = state->a;
uint8_t psw = (state->cc.z |
state->cc.s << 1 |
state->cc.p << 2 |
state->cc.cy << 3 |
state->cc.ac << 4 );
state->memory[state->sp-2] = psw;
state->sp = state->sp - 2;
}
break;

```

### SPHL and XTHL

There are 2 more instructions in the Stack group, SPHL and XTHL.

• `SPHL` moves HL to SP (making the SP have a new address).

• `XTHL` exchanges whatever is on the top of the stack with whatever is in the HL register pair. Why would you want to do that? I don't know.

← Prev: io-and-special-group   Next: more-about-binary-numbers →

Post questions or comments on Twitter @realemulator101, or if you find issues in the code, file them on the github repository.