开发者

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


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'


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


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


>>> 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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜