Python inserting a short integer into a list of bytes

list, python

Solution

You can use the `struct` module to pack values into appropriate formats:

>>> pkt_bytes = [0x02, 0x07, 0xff, 0xff, 0x00, 0x03]
>>> myint = 123
>>> pkt_bytes[3:5] = [ord(b) for b in struct.pack("H",myint)]
>>> pkt_bytes
[2, 7, 255, 123, 0, 3]

By default this will use the native byte order but you can override this using modifiers to format string. Since your variable is called `pkt_bytes` I'm guessing you want network (big-endian) byte order which is signified by a `!`:

>>> struct.pack("!H",5000)
'\x13\x88'

Problem

I have a list of bytes as follows ``` pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03] ``` in the position `0xff,0xff` I want to put a 16bit short integer How do I do it Regards

Original source