Skip to content

[Suggestion]: My C++ version of the checksum algorithm should it help anyone #13

Open
@hashborgir

Description

@hashborgir

This is ready to be built in VS2022.

#define _CRT_SECURE_NO_DEPRECATE

#include <iostream>
#include <stdio.h>
#include<string>

using namespace std;

char** argv = NULL;

void main(int argc, char** argv)
{
	if (argv[1] == NULL) {
		cout << "\n\n\tNo .d2s file specified. \n\n\tUsage: d2scs.exe char.d2s\n\n" << endl;
		return;
	}

	FILE* charFile;
	charFile = fopen(argv[1], "r+b");

	// zero out the previous checksum
	char zero[4] = { 0 };
	fseek(charFile, 12, SEEK_SET);
	fwrite(zero, sizeof(char),sizeof(zero), charFile);
	fflush(charFile);
	fseek(charFile, 0, SEEK_SET);

	unsigned char saveFileData[16];
	unsigned long counter = 0;
	unsigned int uSum = 0;

	int n;
	int uVar = 0;
	int byte;

	while ((n = fread(saveFileData, sizeof(char), 16, charFile)) > 0) {
		int i;
		for (i = 0; i < n; i++) {
			// Current byte in charFile		
			byte = (unsigned)saveFileData[i];

			//SAME as uSum  line, just to double check if both produce the same checksum
			if (uVar < 0)
				byte++;
			uVar = byte + uVar * 2;

			//SAME as above block, just to double check if both produce the same checksum
			uSum = ((uSum << 1) | (uSum >> 31)) + (unsigned)saveFileData[i];
		}
		counter += 16;
	}
	
	unsigned long r_uVar = _byteswap_ulong(uVar);
	unsigned long r_uSum = _byteswap_ulong(uSum);

	// write new checksum
	fseek(charFile, 12, SEEK_SET);
	fwrite(&uVar, sizeof(uVar), 1, charFile);
	fflush(charFile);
	fseek(charFile, 0, SEEK_SET);

	printf("\n\n\t%08x checksum written to %s\n\n", r_uVar, argv[1]);

	fclose(charFile);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions