有人能把这段代码翻译成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;
}
我有一个rotate left函数(
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 - 从c到python的crc24,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4544154/