代码之家  ›  专栏  ›  技术社区  ›  codeasone

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

  •  4
  • codeasone  · 技术社区  · 14 年前

    我有一个字节列表,其中包含一段使用pythonpcapy包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循环中看到的,我将字节写入文件的顺序与从线路处理字节的顺序相同(即网络顺序或大端顺序)。

    我想我需要将它们转换成小端字节顺序,但不确定用Python实现这一点的最佳方法。

    对我来说,解决方案是(适当地编写处理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 struct模块,特别是:

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

    3 回复  |  直到 14 年前
        1
  •  1
  •   John Machin Santi    14 年前

    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(bytes)是“large”,那么

    f.write(struct.pack('%dB' % len(bytes), *bytes)) 
    
        2
  •  2
  •   Scott Griffiths    14 年前

    为了节省一些工作,你可以使用 bytearray (Python 2.6及更高版本):

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

    这会将0-255的值转换成字节,而不需要所有的循环。

    如果没有更多的信息,我看不出你还有什么问题。如果数据真的是字节型的,那么endianness就不是问题了,正如其他人所说的那样。

    (顺便说一下,使用 bytes file

        3
  •  0
  •   Community CDub    7 年前

    这可能已经在以前的文章中得到了回答 Python File Slurp w/ endian conversion .