在一些本田车辆中存在用于网络的校验和算法,其针对所提供的数据计算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
Run Code Online (Sandbox Code Playgroud)
我的版本,在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;
}
Run Code Online (Sandbox Code Playgroud)
不,问题是模数.Python遵循右操作数的符号,C遵循左边的符号.用0x0f掩码来避免这种情况.
result = 8 - result;
result &= 0x0f;
Run Code Online (Sandbox Code Playgroud)