Search code examples
pythonpython-3.xhexmodbus

Convert ASCII Hex to Actualy Real Hex with Crc16(Modbus)


I'm sorry for my bad english. For a project, I am sending and reading data by adding Crc-16(Modbus) codes to the end of the hex codes. My problem is that it detects hex codes as ASCII. I want that hex codes actually hex.

This is ASCII

I want this

For example: This is my hex code --> FE0300010000

This is with Crc-16(Modbus) --> FE03000100000E39 (added 0E39)

But Crc-16 must be "0500" not "0E39". This is happening because python thinks it's ASCII but i need to make it real hex.

I tried convert to bytes and hex again but didn't work also tried binascii.hexlify didn't work as well...


Solution

  • Here answer that i found if anyone need it

    def crc16_modbus(data: bytes) -> int:
        poly = 0xA001
        crc = 0xFFFF
        for b in data:
            crc ^= b
            for i in range(8):
                if crc & 0x0001:
                    crc = (crc >> 1) ^ poly
                else:
                    crc >>= 1
        return crc