【问题标题】:Converting a checksum algorithm from Python to C将校验和算法从 Python 转换为 C
【发布时间】: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;
}

【问题讨论】:

    标签: c checksum


    【解决方案1】:

    不,问题是模数。 Python 遵循右操作数的符号,而 C 遵循左操作数的符号。用 0x0f 掩码来避免这种情况。

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

    【讨论】:

    • @melpomene:刚刚注意到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 2020-04-01
    相关资源
    最近更新 更多