mikip
mikip

Reputation: 1727

Python inserting a short integer into a list of bytes

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

Upvotes: 2

Views: 3080

Answers (4)

David Webb
David Webb

Reputation: 193734

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'

Upvotes: 7

Greg Bacon
Greg Bacon

Reputation: 139631

>>> pkt_bytes = [ 0x02,0x07, 0xff,0xff ,0x00,0x03]
>>> pkt_bytes[2:4] = [pkt_bytes[2] << 8 | pkt_bytes[3]]
>>> pkt_bytes
[2, 7, 65535, 0, 3]

Upvotes: 0

Tendayi Mawushe
Tendayi Mawushe

Reputation: 26138

The code below will replace every occurrence of 0xff with 0x04 until there are no more 0xff left in the list.

pkt_bytes = [0x02, 0x07, 0xff, 0xff ,0x00, 0x03]
while True:
    try:
        idx = pkt_bytes.index(0xff)
        pkt_bytes[idx] = 0x04
    except ValueError:
        break

Upvotes: 0

ars
ars

Reputation: 123548

Try:

>>> pkt_bytes.insert(3, 0xaa)

>>> help(pkt_bytes.insert)
Help on built-in function insert:

insert(...)
    L.insert(index, object) -- insert object before index

Upvotes: 0

Related Questions