问题描述
我需要将以下c代码(计算文件的校验和)转换为python。我写了,对应的代码在python,但结果不匹配c版本。问题是,当溢出发生时,python自动地将int调长,这会导致错误的校验和。
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.
任何想法如何克服这个问题?或者有一个python函数将long转换为signed int32?
Any idea how to overcome this problem ? or is there a python function that converts long to signed int32 ?
感谢
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;
}
解决方案:
感谢所有的帮助。这里是为我工作的函数 -
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
推荐答案
使用或 numpy.uint32
如果你需要限制范围。或者通过 1<< 32
在可能溢出的操作后。
Use numpy.int32
or numpy.uint32
if you need to restrict the range. Or mod it by 1 << 32
after operations that could "overflow".
这篇关于计算校验和的问题:将int转换为signed int32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!