C#, Code, Diablo 2

Understanding the diablo 2 save file format / Part 3

Now , for the third and final part , let’s look into the checksum a bit , i’ll try to keep my code simple and short this time , so you don’t get a headache while trying to read this post πŸ˜‰

On a sidenote , this contains a lot of bitshifting etc. which is not ideal to write in c#, but verything should still be straightforward enough to translate into another language. πŸ™‚

The checksum is actually pretty simple , first of all , you set the checksum bits to 0. ( they are bytes 12-15 )

character.BinaryStream[12] = 0x00;
character.BinaryStream[13] = 0x00;
character.BinaryStream[14] = 0x00;
character.BinaryStream[15] = 0x00;

Now for the checksum algorithm. This one is also fairly simple. All you have to do is add up all the bytes one by one and everytime you add a byte , you bitshift the sum 1 spot to the left. You do however have to make sure to carry over the highest bit( most bitshifting operators do not do this , so we have to do it manually ) , as we do not want this value to get lost , so we actually just rotate our sum around 1 bit everytime we add another value.

uint checksum = 0;            

for (int i = 0; i < character.BinaryStream.Count(); i++)
{
 byte thisByte = character.BinaryStream[i];

 uint carry = 0;
 if ((checksum & (1 << 31)) != 0)
   {
    carry = 1;
   }

checksum = unchecked (unchecked(checksum << 1) + character.BinaryStream[i]) + unchecked(carry) ;
}

And now , we just have to get the checksum back in the 4 bytes!

 byte[] intbytearray = BitConverter.GetBytes(checksum);
character.BinaryStream[12] = intbytearray[0];
character.BinaryStream[13] = intbytearray[1];
character.BinaryStream[14] = intbytearray[2];
character.BinaryStream[15] = intbytearray[3];

If all went well , you should now be able to read in files ,save them out , and still be able to play them !

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s