将校验和算法从 Python 转换为 C

Converting a checksum algorithm from Python to C

某些本田汽车中的网络有一个 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;
}

不对,问题出在模数上。 Python跟在右操作数的符号后面,C跟在左操作数的符号后面。用 0x0f 代替掩码以避免这种情况。

result = 8 - result;
result &= 0x0f;