4

Could someone please explain what the opcode 0x08 does on the LR35902 processor. The mnemonic is LD (a16),SP.

I'm confused because the stack pointer is a 16-bit value but (a16) is an address to somewhere only capable of storing 8 bits (I think!). I could guess that the first 8 bits are placed into (a16) and the next are placed adjacent to those but I would like confirmation.

GabrielOshiro
  • 7,986
  • 4
  • 45
  • 57
user2674487
  • 113
  • 4

1 Answers1

10

Yes, that opcode puts SP value at an address (a16). Here's what it will look like:

void MemoryWrite(uint16_t addr, uint8_t value);

MemoryWrite(a16, SP & 0xFF);
MemoryWrite(a16 + 1, (SP & 0xFF00) >> 8);

Because it's a little-endian processor you put least significant byte first.

creker
  • 9,400
  • 1
  • 30
  • 47
  • Thanks Creker, appreciated! – user2674487 Mar 26 '16 at 22:55
  • MemoryWrite((a16 + 1) & 0xFFFF, (SP & 0xFF00) >> 8); – Méga Lag Mar 27 '16 at 15:19
  • Méga Lag, I see you are anding the address with 0xFFFF, which I believe is to make sure it is positive but I think this is implied by the notation a16. Also, even if I were to and with 0xFFFF shouldn't I do that before doing the + 1? – user2674487 Mar 27 '16 at 23:39
  • 3
    I don't think it's really necessary. First, don't think someone would make a game that writes to an address that would overflow uint16_t. Also, it would overwrite the stack which doesn't look like one would do. Second, uint16_t would just wrap around anyway, it's not an undefined behaviour. – creker Mar 27 '16 at 23:46
  • 1
    @creker Correct! Upon execution of `LD (0xFFFF), SP`, the memory position `0xFFFF` will have SP least significant bits. Memory pointer wraps around and the CPU will attempt to write on memory position `0x0000`. Nothing would happen because `0x0000` is read-only. – GabrielOshiro Mar 29 '16 at 01:12
  • Thank you for the info, now I know I didn't need to do that on my implementation x) – Méga Lag Mar 29 '16 at 17:08
  • 2
    @GabrielOshiro, well, not quite read-only. It wouldn't overwrite anything but could trigger MBC. As you probably know, MBCs are programmed by writing into read-only addresses. For example, writing into 0x0000 would trigger external RAM in MBC1 and trigger RAM/RTC in MBC3. But emulator shouldn't check that anyway. You do what ROM tells you. – creker Mar 29 '16 at 18:31