1

I have a bytearray as follows:

frame = bytearray()
frame.append(0x6)
frame.append(0x8)
frame.append(0xf1)
frame.append(0x1b)
frame.append(0x3)
frame.append(0x2)
frame.append(0x1)
frame.append(0x0)
frame.append(0x0)
frame.append(0x0)

I am applying a CRC on all the bytes of the frame:

seed = 0xB7D2
POLY = 0x8408


class CanCRC:
    def __init__(self, value=0):
        self.value = value

    def update(self, char: bytes, crcres):
        for b in range(8):
            if ((crcres & 0x0001) ^ (char & 0x0001) == 0x0001):
                crcres = crcres >> 1
                crcres ^= POLY
            else:
                crcres = crcres >> 1
            char = char >> 1
        return crcres

can = CanCRC(value=seed)
for i in range(0, len(frame)):
    can.value = can.update(frame[i], can.value)


frame.extend((can.value).to_bytes(2, byteorder='little'))

print(hex(can.value))
print(frame)

The final CRC value is 0xcc30, but when added to the bytearray, the array is showing:

bytearray(b'\x06\x08\xf1\x1b\x03\x02\x01\x00\x00\x000\xcc')

Why would this be? I'm getting \x000\xcc instead of \x30\xcc

I've noticed this happen with other bytes in an array too.. it's not encoding properly or something...

Any help appreciated

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
arsenal88
  • 1,040
  • 2
  • 15
  • 32
  • 2
    Do you know what is the ASCII code for the character `'0'`? It is 48 or 0x30 in hexadecimal. So `b'0'` and `b'\30'` represent exactly the same byte string containing a single `0` character: the arrays shows what you want. – Serge Ballesta Nov 12 '18 at 13:37
  • Start a Python REPL session and type `b'\x30'` and see what happens. – Code-Apprentice Feb 06 '19 at 20:57

0 Answers0