gpt4 book ai didi

python - crc24 从 c 到 python

转载 作者:太空宇宙 更新时间:2023-11-04 07:40:32 25 4
gpt4 key购买 nike

有人可以将这段代码翻译成 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)),我知道这是有效的,因为我是从一个有信誉的程序员的源代码中得到它的,但我没有得到 *++ 在八位字节上。我只知道 ++ 在 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

最佳答案

# 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

关于python - crc24 从 c 到 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4544154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com