将C语言中的crc24转换为Python

1 投票
2 回答
4605 浏览
提问于 2025-04-16 09:07

有人能把这段代码翻译成Python吗?我试了很多次,但一直没成功:

  #define CRC24_INIT 0xB704CEL
  #define CRC24_POLY 0x1864CFBL

  typedef long crc24;
  crc24 crc_octets(unsigned char *octets, size_t len)
  {
      crc24 crc = CRC24_INIT;
      int i;
      while (len--) {
          crc ^= (*octets++) << 16;
          for (i = 0; i < 8; i++) {
              crc <<= 1;
              if (crc & 0x1000000)
                  crc ^= CRC24_POLY;
          }
      }
      return crc & 0xFFFFFFL;
  }

我有一个左旋转的函数(ROL24(value,bits_to_rotate_by)),我知道它是有效的,因为我从一个知名程序员的源代码中得来的。但我不太明白*++在八位字节(octet)上的用法。我只大概理解++在C++中的作用,但对*完全不懂。

我的代码是:

def crc24(octets, length):# now octects is a binary string
 INIT = 0xB704CE
 POLY = 0x1864CFB
 crc = INIT
 index = 0
 while length:
  crc ^= (int(octets[index], 2) << 16)
  index += 1
  for i in xrange(8):
   crc = ROL(crc, 1)
   if crc & 0x1000000:
    crc ^= POLY
  length -= 1
 return crc & 0xFFFFFF

2 个回答

1

我不太懂Python,但可以告诉你,unsigned char *octets 是一个指针(你可以把它想象成一个长度为len的数组)。

*octets 会返回这个数组的第一个元素。

++ 是用来把指针移动到下一个元素的。

所以这一行 crc ^= (*octets++) << 16; 的意思基本上和下面这个伪代码是一样的(index只设置一次为0)。

(global var index = 0)

temp = octets[index] shift left 16 bits
crc = crc bitwise xor temp
index = index + 1
2

当然可以!请看下面的内容:

这段代码的意思是,它会检查某个条件是否成立。如果条件成立,就会执行一段特定的代码;如果条件不成立,就会执行另一段代码。简单来说,就是根据不同的情况,程序会做出不同的反应。

在编程中,这种根据条件来决定执行什么操作的方式,叫做“条件语句”。它就像是生活中的选择题,根据你选择的答案,结果会有所不同。

希望这个解释能帮助你更好地理解这段代码的作用!

# Yes, there is no 'length' parameter here. We don't need it in Python.
def crc24(octets):
    INIT = 0xB704CE
    POLY = 0x1864CFB
    crc = INIT
    for octet in octets: # this is what the '*octets++' logic is effectively
    # accomplishing in the C code.
        crc ^= (octet << 16)
        # Throw that ROL function away, because the C code **doesn't** actually
        # rotate left; it shifts left. It happens to throw away any bits that are
        # shifted past the 32nd position, but that doesn't actulaly matter for
        # the correctness of the algorithm, because those bits can never "come back"
        # and we will mask off everything but the bottom 24 at the end anyway.
        for i in xrange(8):
            crc <<= 1
            if crc & 0x1000000: crc ^= POLY
    return crc & 0xFFFFFF

撰写回答