0

I am trying to use crcmod correctly but I have problem: For example I would like to transform the string "1234567809" into the bytes b'\x12\x34\x56\x78\x09' in order to obtain the correct crc16 modbus code.

import crcmod

crc16 = crcmod.mkCrcFun(0x18005, rev=True, initCrc=0xffff)
for i in range(len(a)//2):
    a = a[:(i*4)] + r"\x" + a[i*4:]

The problem is that r"\x" inserts '\\x', not '\x', and of course '\x' returns an error.

a.encode("utf-8")

of course returns b'\\x12\\x34\\x56\\x78\\x09'.

That is the result with \\x:

hex(crc16(a.encode("utf-8")))
'0x68b7'

That is the result I expected:

hex(crc16(b'\x12\x34\x56\x78\x09'))
'0x2590'
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Fred I. R.
  • 111
  • 2
  • 1
    `r"\x"` *does* insert the two characters `\x`, but when it is printed to the terminal, the character ```\``` is sometimes shown as ```\\```. – mkrieger1 Apr 04 '22 at 13:15

1 Answers1

2

You can directly convert a string: '1234567809' to the bytes you want:

source = '1234567809'
a = bytes.fromhex(source)

Now the crc should work:

hex(crc16(a))
quamrana
  • 37,849
  • 12
  • 53
  • 71