【发布时间】:2018-05-28 18:52:40
【问题描述】:
对于某些本田汽车中的网络,有一个 checksum algorithm,它为提供的数据计算 0-15 之间的整数。我正在尝试将其转换为纯 C,但我认为我遗漏了一些东西,因为我在实现中得到了不同的结果。
虽然 Python 算法为“ABC”计算 6,但我的计算结果为 -10,这很奇怪。我是不是把位移弄乱了?
Python 算法:
def can_cksum(mm):
s = 0
for c in mm:
c = ord(c)
s += (c>>4)
s += c & 0xF
s = 8-s
s %= 0x10
return s
我的版本,在 C 中:
int can_cksum(unsigned char * data, unsigned int len) {
int result = 0;
for (int i = 0; i < len; i++) {
result += data[i] >> 4;
result += data[i] & 0xF;
}
result = 8 - result;
result %= 0x10;
return result;
}
【问题讨论】: