Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
byte[] array = { 0x01, 0x03, 0x00, 0x01, 0x00, 0x01 };
ushort u = CRC(array);
Console.WriteLine(u.ToString("X4"));
Python
def CalculateCRC(data):
crc = 0xFFFF
for pos in data:
crc ^= pos
for i in range(len(data)-1, -1, -1):
if ((crc & 0x0001) != 0):
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc
Which I run like this:
data = bytearray.fromhex("010300010001")
crc = CalculateCRC(data)
print("%04X"%(crc))
The result from the C# example is: 0xCAD5.
The result from the Python example is: 0x8682.
I know from fact by other applications that the CRC should be 0xCAD5, as the C#-example provides.
When I debug both examples step-by-step, the variable 'crc' has difference values after these code lines:
crc ^= (UInt16)data[pos];
crc ^= pos
What am I missing?
/Mc_Topaz
Your inner loop uses the size of the data array instead of a fixed 8 iterations. Try this:
def calc_crc(data):
crc = 0xFFFF
for pos in data:
crc ^= pos
for i in range(8):
if ((crc & 1) != 0):
crc >>= 1
crc ^= 0xA001
else:
crc >>= 1
return crc
data = bytearray.fromhex("010300010001")
crc = calc_crc(data)
print("%04X"%(crc))
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.