2

I would like to know if it's possible to modify an already made struct. What I want is to calculate the CRC of header and then write the CRC value to the 3rd position in header.

import struct
import crcmod

crcfunc = crcmod.mkCrcFun(0x112, 0x00, 0x00)
header = struct.pack('!hii', 1, 2, 0)
crcvalue = crcfunc(header)
1
  • Don't forget to select an answer. Commented Nov 26, 2020 at 4:31

2 Answers 2

2

Since the result of calling struct.pack is to create a byte string, it is immutable.

You could either splice the crc into the byte string by slicing it, or create a new byte string:

header2 = struct.pack('!hii', 1, 2, crcvalue)

Alternatively, if you want to create a mutable byte string, you could create a buffer, and use struct.pack_into instead of struct.pack.

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

1 Comment

pack_into is the way to go. +1
2

You can not do it directly: struct.pack returns a bytes object, which like str, is immutable. However, you can very easily create the updated object:

header = header[:-4] + c.to_bytes(4, byteorder=sys.byteorder)

If you really meant to compute the CRC value on everything excluding the last element, you can do something like this instead:

header = struct.pack('!hi', 1, 2)
header += crcfunc(header).to_bytes(4, byteorder=sys.byteorder)

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.