3

I need to convert the following c code (to calculate checksum for a file) to python. I had written, the corresponding code in python but the result didn't match the c version. The problem was that python autmatically promotes int to long whenever overflow occurs and this results in wrong checksums.

Any idea how to overcome this problem ? or is there a python function that converts long to signed int32 ?

Thanks

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;
}

Solution:

Thanks for all the help. Here's the function that worked for me -

 def int32(x):
    x = 0xffffffff & x
    if x > 0x7fffffff :
        return - ( ~(x - 1) & 0xffffffff )
    else : return x 
2
  • Isn't there something missing in the c code? data / p seems to be used in a very odd way... Commented Feb 20, 2010 at 2:11
  • Sorry, had accidently removed '+' during formatting. Corrections made . thanks Commented Feb 20, 2010 at 2:20

1 Answer 1

2

Use numpy.int32 or numpy.uint32 if you need to restrict the range. Or mod it by 1 << 32 after operations that could "overflow".

Sign up to request clarification or add additional context in comments.

2 Comments

Or & 0xFFFFFFFF (& ((1<<32)-1)). I happen to like that more, but it does the exact same as % (1 << 32).
Its not just about extracting the lower 32 bits, but the sign also needs to be considered - the way java handle the overflow. e.g. int i = 0xffffffff; system.out.println(i) would give -1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.