用于将网络中的字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了用于将网络中的字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2081字,纯文字阅读大概需要3分钟。
内容图文
![用于将网络中的字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法](/upload/InfoBanner/zyjiaocheng/783/6fbb400aa59d451295cb5e26665ec432.jpg)
我目前的任务是剖析包含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))
内容总结
以上是互联网集市为您收集整理的用于将网络中的字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法全部内容,希望文章能够帮你解决用于将网络中的字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。