0

I am examining a .d2s file using HxD, which lets me see the unencoded bytes of the file.

The file is about 900+ bytes.

Bytes 12 to 15 are a checksum.

The algorithm for calculating the checksum is as follows:

sum = (sum << 1) + data[i];

And here is the github page where I got that formula.

https://github.com/krisives/d2s-format#checksum

A lot of other websites report that this is the correct formula for this type of file, so I am confident it is right. But I am having a hard time understanding and implementing it so that I get a sensible result.

<< is a binary shift to the left, and if I do (sum << 1), I'm shifting the current checksum (in binary) to the left by 1 position (or multiplying the decimal equivalent by 2) before I add the next byte.

But I have 900 bytes in the file. I'm getting a HUGE number (way bigger than something that will fit inside 4 bytes or 32 bits or 2^32), which is correct given my understanding. So I think I am wrong about this.

Here is a fiddle where I try to calculate the checksum:

http://jsfiddle.net/yghceL3n/

I just copy the contents of the file and paste them into the textarea and the checksum gets output to the page and the console.

This whole exercise is for learning purposes.

dactyrafficle
  • 838
  • 8
  • 18
  • 3
    The value you're calculating needs to be truncated, or wrapped around a uint32. – Jonathon Reinhart Aug 21 '18 at 01:34
  • 1
    You are correct, is like multiplying with x2, and you'll get a very big number, and you'll get overflow (more: [here](https://stackoverflow.com/questions/1597585/bit-shifting-in-internet-checksums) ). No worries. The checksum it is still correct. Using your algorithm, no matter how big the file is, you'll still get the uint32 size. – azbarcea Aug 21 '18 at 01:42
  • what does it mean to 'wrap around a uint32' ? – dactyrafficle Aug 21 '18 at 01:45
  • 2
    In JavaScript terms, `checksum = ((checksum << 1) + y) & 0xFFFF` – Amadan Aug 21 '18 at 02:05
  • That's only 16 bits, 32 bits would be `0xFFFFFFFF` – user3386109 Aug 21 '18 at 02:15
  • Derp. What @user3386109 wrote is correct. – Amadan Aug 21 '18 at 08:21
  • would the above recommendations production the result as the following (in js): `checksum = checksum*2 + y; checksum = checksum % Math.pow(2, 32);` where `checksum` and `y` are reported in their decimal representations. And once the calc is done, I convert back to hex? – dactyrafficle Aug 22 '18 at 03:40

0 Answers0