开发者

Python byte buffer object?

开发者 https://www.devze.com 2023-03-24 08:26 出处:网络
Is there a byte buffer object in Python to which I can append values of specific types? (preferably with specifiable endianess)

Is there a byte buffer object in Python to which I can append values of specific types? (preferably with specifiable endianess)

For example:

buf.add_int(4)    # should add a 4 byte integer
buf.add_short(10) # should add a 2 byte short
buf.add_byte(24)  # should add a byte

I know that I could just use开发者_Python百科 struct.pack but this approach just seems easier. Ideally it should be like the DataOutputStream and DataInputStream objects in Java which do this exact task.


You can always use bitstring. It is capable of doing all the things you ask and more.

>>> import bitstring
>>> stream=bitstring.BitStream()
>>> stream.append("int:32=4")
>>> stream.append("int:16=10")
>>> stream.append("int:8=24")
>>> stream
BitStream('0x00000004000a18')
>>> stream.bytes
'\x00\x00\x00\x04\x00\n\x18'

Here is a link to the documentation.


As Kark Knechtel suggests you'll have to make your own type that handles this. Here's a quick extension of bytearray:

import struct

class DataStream(bytearray):

    def append(self, v, fmt='>B'):
        self.extend(struct.pack(fmt, v))

>>> x = DataStream()
>>> x.append(5)
>>> x
bytearray(b'\x05')
>>> x.append(-1, '>i')
>>> x
bytearray(b'\x05\xff\xff\xff\xff')


Just wrap up the struct.pack logic in your own class.

0

精彩评论

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

关注公众号