Reputation: 642
I have some technical documentation and try to replicate the given CRC algorithm in python. However I don't get the correct results. How do I have to tweak my algo to match the docs?
This is the documentation:
And this is my code:
data1 = b'\0x01\0x04\0x00\0x0b\0x00\0x01'
data2 = b'\0x01\0x03\0x00\0x65\0x00\0x01'
def crc16(data : bytearray):
length = len(data)
crc = 0xffff
for i in range(0, length):
crc ^= data[i]
for j in range(0,8):
if (crc & 0x01):
crc =(crc >> 1) ^ 0xa001
else:
crc = crc >> 1
return crc
print(crc16(data1).to_bytes(2, 'big'))
print(crc16(data2).to_bytes(2, 'big'))
Here are some examples for the documentation:
Here are my results:
b'\xc9Y'
b'\xd4\xd1'
Upvotes: 0
Views: 90
Reputation: 3649
Your input data is wrong. The first one should be b'\x01\x04\x00\x0b\x00\x01'
for example. The first string as written by you has '\0'
(a null character), followed by the literal characters 'x04'
, and so on. You can check this by printing the strings.
Once this is corrected your code appears to give the correct results.
As a minor note, your type information for the data
parameter says it takes a bytearray
but you're actually passing it bytes
.
Upvotes: 1