crc24 from c to python
can someone please translate this code to python? i have tried and tried again, but have not managed it:
#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;
}
i have the rotate left function (开发者_如何学JAVAROL24(value,bits_to_rotate_by)
), which i know works since i got it from a source code of a reputable programmer, but i dont get the *
and ++
on octet. i only sort of understand how ++
works in c++, and i dont know what *
is at all
my code is:
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
I don't know python but unsigned char *octets
is a pointer (you can think of it as an array of size len).
*octets
returns the first element.
the ++
moves the point to the next element.
so the line crc ^= (*octets++) << 16;
is basically the same as this pseudo code (index is set to 0 once.)
(global var index = 0)
temp = octets[index] shift left 16 bits
crc = crc bitwise xor temp
index = index + 1
精彩评论