Skip to content

Instantly share code, notes, and snippets.

@BrentFarris
Last active November 30, 2021 04:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BrentFarris/77732ed16177da80fbddbf518d49aea4 to your computer and use it in GitHub Desktop.
Save BrentFarris/77732ed16177da80fbddbf518d49aea4 to your computer and use it in GitHub Desktop.
Game Boy Cartridge ROM Checksum code
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
int main(int argc, char** argv) {
FILE* fp = fopen(argv[1], "rb");
if (fp == NULL) {
printf("Failed to open the file to read: %s\n", argv[1]);
return -1;
}
fseek(fp, 0L, SEEK_END);
size_t len = ftell(fp);
rewind(fp);
uint8_t* buff = malloc(len);
if (buff == NULL) {
printf("Failed to allocate %zu bytes of memory", len);
return -2;
}
fread(buff, len, 1, fp);
fclose(fp);
size_t sum = 0;
buff[0x14E] = 0;
buff[0x14F] = 0;
for (size_t i = 0; i < len; ++i) {
sum += buff[i];
}
buff[0x14E] = ((uint8_t*)&sum)[1];
buff[0x14F] = ((uint8_t*)&sum)[0];
fopen(argv[1], "wb");
if (fp == NULL) {
printf("Failed to open the file to write: %s\n", argv[1]);
return -3;
}
fwrite(buff, len, 1, fp);
fclose(fp);
return 0;
}
@BrentFarris
Copy link
Author

Compile with clang:

clang -O2 gbsum.c -o gbsum

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment