This week I encountered some difficulties when it actually came time to write some code for my capstone project, the Space Invaders Emulator.
As I’ve written about in previous posts, my team is writing a space invaders emulator in C++. I have almost no experience with C++, so going into this class I knew I’d have to spend some time learning C++ before I could even write some code.
For the first portion of our project we have to write a disassembler that will read the binary files (the ROM) of the game and translate them into assembly code. We have to do this so we can see what type of operations the game would use on the processor so we can emulate them in C++. So for the first week we all agreed we would try and write our own version of the disassembler to help everyone get familiar and write some code. At the end of the week, we’d all compare our code and the best disassembler would be committed to the project.
It didn’t take long for me to get hung up writing code in C++. For example, if you wanted to read and view the contents of a binary file in Python, you could accomplish it with the following 3 lines of code:
file = open(“document.bin”,”rb”)
print(file.read(4))
file.close()
Pretty straight forward right? Nothing to tricky here. If you google “how to read a binary file in c++” like I did this week, here’s the top result you’ll get from stack overflow:
#include <fstream>
#include <vector>
typedef unsigned char BYTE;
std::vector<BYTE> readFile(const char* filename)
{
// open the file:
std::streampos fileSize;
std::ifstream file(filename, std::ios::binary);
// get its size:
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
// read the data:
std::vector<BYTE> fileData(fileSize);
file.read((char*) &fileData[0], fileSize);
return fileData;
}
That’s 12 lines of code! This is certainly just one way to do it, but I think you get the point. I spent a few hours working through this example. Although I could read the code and have a rough idea of what’s happening, it was hard for me to understand why any of it was necessary.
C++ is so verbose it can be hard to engage with as a newbie, but there are a lot of reasons you’d still want to write an emulator with it. Mostly because of it’s speed and precision. Often described as “C with classes”, C++ can tackle low level programming problems that you couldn’t do with Python because in Python the operations are too abstracted. For example, in Python there is only 1 integer type. In C++ there are 28 that I could count (reference).
I definitely have my work cut out for me at this point. My real project for the quarter is becoming proficient in C++; writing an emulator will just be a side affect of pursing that goal. And it’s all going to pay dividends when I start my new job in April.