开发者

Problem in calculating checksum : casting int to signed int32

开发者 https://www.devze.com 2022-12-20 14:33 出处:网络
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 py

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 


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号