I need to convert the following c code (to calculate the checksum for a file) to python. I wrote the appropriate code in python, but the result did not match c version. The problem was that python automatically advances int to infinity when an overflow occurs, and this leads to incorrect checksums.
Any ideas how to overcome this problem? or is there a python function that takes a long time to convert to a signed int32?
thank
int calcChecksum(const guchar *data, gsize len)
{
const guchar *p = data;
int checksum = 0, g, i = len;
while(i--) {
checksum = (checksum << 4) + *p++;
if((g = (checksum & 0xf0000000)) != 0)
checksum ^= g >> 23;
checksum &= ~g;
}
return checksum;
}
Decision:
Thanks for the help. Here is the function that worked for me -
def int32(x):
x = 0xffffffff & x
if x > 0x7fffffff :
return - ( ~(x - 1) & 0xffffffff )
else : return x
source
share