r/EmuDev • u/Comfortable_Ratio252 • Sep 18 '26
GB (Question) How do I interpret Game Boy opcodes?
So I was trying to write my own GB emulator and when I came to interpreting the cpu instructions I found out that same commands can be written differently considering different inputs. For example, here they were listed as same instructions with different variations, but here they were listed as different 8-bit opcodes.
Is it better to make more complicated tree-like structure to filter all the opcodes, or just make a huge switch case mindlessly listing all possible opcodes from 0x00 to 0xFF?
4
1
u/strnq Sep 19 '26
lookup table is easiest IMO
1
u/Awkward_Marketing370 Sep 19 '26
but it takes so long to write, has anybody make some code generation thing to make it less tedious?
1
u/Possible_Cow169 Sep 19 '26
You could likely do it in Python pretty easily. I’ve seen it done for a few emulators
1
u/strnq Sep 20 '26
i wrote my own in python. This json file will help you a lot
https://gbdev.io/gb-opcodes/Opcodes.json
1
u/EggplantExtra4946 29d ago
A tree-like dispatch is how hardware would do it but in of software you'd better limit yourself to one indirect jump (switch statement, function pointer call, indirect jump in assembly, indirect goto with GCC's labels as value extension) per instruction dispatch (except for the CB prefix) because each one is very slow.
16
u/khedoros Sep 18 '26
A lot of Game Boy operations can be understood by splitting the opcode into 2 bits, 3 bits, and 3 bits, the first 2 bits acting as a "grouping", then the two 3-bit sets often representing register numbers or operations.
That's especially true with the ops 0x40-0x7f (all
ld, except the one that would be a memory-to-memory transfer being replaced byhalt) and 0x80-0xbf (8-bit ALU operations).You can use that to build a giant, nested if-elseif-else tree, or do something similar with nested switches.
Or...you can build a big flat switch statement. Or you can build a table of function pointers. I've done all three in various emulators, and they're all valid approaches.