Skip to content

Instantly share code, notes, and snippets.

@Jim-Holmstroem
Last active January 31, 2024 00:54
Show Gist options
  • Save Jim-Holmstroem/0b487024003cc1aed2ff to your computer and use it in GitHub Desktop.
Save Jim-Holmstroem/0b487024003cc1aed2ff to your computer and use it in GitHub Desktop.
Checksum for diablo 2 files .d2s in python (todo insert the checksum into the file)
import numpy as np
"""
code to replicate:
static int d2charsave_checksum(unsigned char const *data, unsigned int len, unsigned int offset)
{
int checksum;
unsigned int i;
unsigned int ch;
if (!data) return 0;
checksum=0;
for (i=0; i<len; i++) {
ch=data[i];
if (i>=offset && i<offset+sizeof(int)) ch=0;
ch+=(checksum<0);
checksum=2*checksum+ch;
}
return checksum;
}
"""
def d2charsave_checksum(filename, offset=12):
def checksum(data, start_value=0):
acc = np.int32(start_value)
for value in data:
acc = np.int32((acc << 1) + value + (acc<0))
return np.int32(acc)
data = np.fromfile(filename, dtype=np.uint8)
checksum_byte_length = np.dtype("int32").itemsize
pre_data, post_data = data[:offset], data[offset + checksum_byte_length:]
pre_checksum = checksum(
pre_data,
start_value=0
)
on_checksum = checksum(
np.zeros(checksum_byte_length, dtype=np.uint8),
start_value=pre_checksum
)
post_checksum = checksum(
post_data,
start_value=on_checksum
)
return post_checksum
def main():
checksum = d2charsave_checksum("items.d2s")
print((checksum, 343162958))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment