I need to calculate the crc8 dvb s2 checksum in python but I can't find any useful information on how this checksum really works, so I tried to convert this working C code:
uint8_t crc8_dvb_s2(uint8_t crc, unsigned char a)
{
crc ^= a;
for (int ii = 0; ii < 8; ++ii) {
if (crc & 0x80) {
crc = (crc << 1) ^ 0xD5;
} else {
crc = crc << 1;
}
}
return crc;
}
in python code:
import crc8
import operator
def bxor(b1, b2): # use xor for bytes
return bytes(map(operator.xor, b1, b2))
def blshift(b1, b2): # use shift left for bytes
return (int.from_bytes( b1, byteorder='little') << int.from_bytes( b2, byteorder='little')).to_bytes(1, byteorder='little')
def _checksum(message):
#calculate crc
crc = crc8.crc8()
crc.update(message)
crc_result = crc.digest()
#calculate dvb
crc_result = bxor(crc_result , message)
for i in range(0, 7):
if (crc_result == b'\x80') :
crc_result = bxor((blshift(crc_result, b'\x01')) , b'\xD5')
else:
crc_result = blshift(crc_result, b'\x01')
#-------------
return crc_result;
But there is something wrong with it that I can't seem to understand. If I give the C function the bytes '\x00d\x00\x00\x00' it gives my as a result '\x8f' ( which is right), while the Python function gives me the OverflowError: int too big to convert.
There's clearly something wrong with my code that makes the numbers bigger and bigger but I wasn't able to figure out what exactly.
Full backtrace:
---------------------------------------------------------------------------
OverflowError Traceback (most recent call last)
<ipython-input-226-8288eada1ce9> in <module>
----> 1 _checksum(b'\x00d\x00\x00\x00')
<ipython-input-225-2e5beaea293f> in _checksum(message)
18 crc_result = bxor((blshift(crc_result, b'\x01')) , b'\xD5')
19 else:
---> 20 crc_result = blshift(crc_result, b'\x01')
21 #-------------
22 return crc_result;
<ipython-input-225-2e5beaea293f> in blshift(b1, b2)
6 return bytes(map(operator.and_, b1, b2))
7 def blshift(b1, b2): # use shift left for bytes
----> 8 return (int.from_bytes( b1, byteorder='little') << int.from_bytes( b2, byteorder='little')).to_bytes(1, byteorder='little')
9 def _checksum(message):
10 #calculate crc
OverflowError: int too big to convert