Gameboy Processor LR35902 Opcode 0x08 Meaning
Asked Answered
J

1

5

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.

Jenn answered 26/3, 2016 at 20:59 Comment(0)
B
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.

Bible answered 26/3, 2016 at 22:21 Comment(7)
Thanks Creker, appreciated!Jenn
MemoryWrite((a16 + 1) & 0xFFFF, (SP & 0xFF00) >> 8);Dubose
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?Jenn
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.Bible
@Bible 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.Rasmussen
Thank you for the info, now I know I didn't need to do that on my implementation x)Dubose
@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.Bible

© 2022 - 2024 — McMap. All rights reserved.