将网络字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法

标签 python file-io binary endianness byte

我目前的任务是剖析包含 P2P 消息的 tcpdump 数据,我在获取和写入 x86 机器上的文件的片段数据时遇到了问题。我怀疑我写入文件的字节有一个简单的字节顺序问题。

我有一个字节列表,其中包含一段使用 python-pcapy 包 BTW 读取和处理的 P2P 视频。

bytes = [14, 254, 23, 35, 34, 67, etc...]

我正在寻找一种方法来存储这些字节,这些字节目前保存在我的 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

我想我需要将它们转换为小端字节顺序,但不确定在 Python 中实现此目的的最佳方法。

更新

为我解决的解决方案(编写 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 struct 模块,特别是:

    little = struct.pack('<'+'B'*len(bytes), *bytes) 

感谢那些提供有用建议的人。

最佳答案

为了节省一些工作,您可能喜欢使用 bytearray (Python 2.6 及更高版本):

b = [14, 254, 23, 35]
f = open("file", 'ab')
f.write(bytearray(b))

这会将您的 0-255 值全部转换为字节,而无需所有循环。

如果没有更多信息,我看不出你的问题是什么。如果数据确实是按字节排列的,那么字节顺序就不是问题,正如其他人所说。

(顺便说一句,使用 bytesfile 作为变量名并不好,因为它隐藏了同名的内置函数)。

关于将网络字节列表(big-endian)字节顺序存储到文件(little-endian)的Python方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3405972/

相关文章:

iphone - 我应该使用哪种文件格式将数组保存到文件中?

c - 更新和删除文件内容

python - 从 csv 文件读取数据框时如何设置列?

python - Mako 从字符串调用函数?

Java OutputStream 到多个文件

binary - 只用 NAND 门合成左移 1?

数据库索引和查找与 "closest neighbour"不完全匹配

php - 我如何对这些 base64 数字进行异或运算?

javascript - 在javascript中乘以4x3仿射变换矩阵

python - 与 mod_wsgi 相比, mod_python "work"怎么样?