标签:python file-io binary byte endianness
我目前的任务是剖析包含P2P消息的tcpdump数据,我遇到的问题是我获取并写入x86机器上的文件.我的怀疑是我有一个简单的字节序问题,我写入文件的字节.
我有一个字节列表,持有一段P2P视频读取和处理使用python-pcapy包BTW.
bytes = [14,254,23,35,34,67等…]
我正在寻找一种方法来存储这些字节,目前保存在我的Python应用程序的列表中的文件中.
目前我写的作品如下:
def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts):
file = open(filename,"ab")
# Iterate through bytes writing them to a file if don't have piece already
if not self.piecemap[ipdst].has_key(pieceindex):
for byte in bytes:
file.write('%c' % byte)
file.flush()
self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename))
# Remember we have this piece now in case duplicates arrive
self.piecemap[ipdst][pieceindex] = True
# TODO: Collect stats
file.close()
正如您在for循环中看到的那样,我将字节写入文件的顺序与从线程处理它们的顺序相同(即网络或大端顺序).
可以说,作为片段有效载荷的视频在VLC中不能很好地播放:-D
我想我需要将它们转换为little-endian字节顺序,但我不确定在Python中处理它的最佳方法.
UPDATE
为我设计的解决方案(编写适当处理endian问题的P2P片段)是:
def writePiece(self, filename, pieceindex, bytes, ipsrc, ipdst, ts):
file = open(filename,"r+b")
if not self.piecemap[ipdst].has_key(pieceindex):
little = struct.pack('<'+'B'*len(bytes), *bytes)
# Seek to offset based on piece index
file.seek(pieceindex * self.piecesize)
file.write(little)
file.flush()
self.procLog.info("Wrote (%d) bytes of piece (%d) to %s" % (len(bytes), pieceindex, filename))
# Remember we have this piece now in case duplicates arrive
self.piecemap[ipdst][pieceindex] = True
file.close()
解决方案的关键是怀疑使用Python结构模块,特别是:
little = struct.pack('<'+'B'*len(bytes), *bytes)
感谢那些回复了有用建议的人.
解决方法:
您还可以使用array.array:
from array import array
f.write(array('B', bytes))
代替
f.write(struct.pack('<'+'B'*len(bytes), *bytes))
当整理一点时
f.write(struct.pack('B' * len(bytes), *bytes))
# the < is redundant; there is NO ENDIANNESS ISSUE
如果len(字节)是“大”可能会更好
f.write(struct.pack('%dB' % len(bytes), *bytes))
标签:python,file-io,binary,byte,endianness 来源: https://codeday.me/bug/20190701/1342043.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。