1

I've got a frame build like this : {0x00, 0x00, 0x00, 0x00, 0x00}.

C# script to calculate crc8

   u8 Crc(u8 *buffer, u8 length) 
   {
        u8 crc = 0, idx;
        while ( length-- != 0 ) 
        {
            crc = crc ^ *buffer++;
            for ( idx = 0; idx < 8; ++idx ) 
            {
                if ( crc & 0x01 ) crc = (crc >> 1) ^ 0x8C;
                else crc >>= 1;
            }
       }
       return crc;
    }

can someone show me how to write it correctly in Python?

2
  • That Tkinter stuff is irrelevant to the CRC calculation. Commented Jun 15, 2018 at 11:05
  • Where did you get this crc8 algorithm? The bitshift directions and polynomial seem odd. Commented Jun 15, 2018 at 11:16

1 Answer 1

2

The site you linked appears to use the same algorithm as what you've posted. It's easy enough to translate to Python, all of the bit twiddling code remains the same, all you need to change is the code that loops over the input buffer.

def crc8(buff):
    crc = 0
    for b in buff:
        crc ^= b
        for i in range(8):
            if crc & 1:
                crc = (crc >> 1) ^ 0x8C
            else:
                crc >>= 1
    return crc

buff = [0x12, 0xAB, 0x34]
crc = crc8(buff)
print(hex(crc))

output

0x17

This code also works correctly if buff is a bytes or bytearray object.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.