最近因项目需要要在Python里面使用ByteArray,于是用struct封装了一下:
import struct
class ByteArray:
"""
A class to simulate ByteArray.
@author
tyraeltong@gmail.com @attention call writexxx(),last call getContent() to get result.
"""
m_cont=[]
def writeByte(self, b):
self.m_cont.append(struct.pack('B', b))
def writeShort(self, s):
self.m_cont.append(struct.pack('H', s))
def writeInt(self, i):
self.m_cont.append(struct.pack('I', i))
def writeString(self, s):
self.m_cont.append(s)
def getContent(self):
return ''.join(self.m_cont)
奇怪的是struct的's'format,好像对字符串并不起作用,下面的语句:
struct.pack('s', 'abcd')
只会返回 'a'