如何在Python中读取位流中的字符串

2024-09-30 01:22:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在输出文件中写入以下字符串:

bitstream.add("stri", 32)

在哪里

def add(self, data, length):
    s = ''
    if (type(data) == str):
        for char in data:
            b = bin(ord(char))[2:]
            s = s + "{:0>8}".format(b)
    else:
        s = bin(data)[2:]
        if (len(s) < length):
            resto = length - len(s)
            for _ in range(0, resto):
                s = '0' + s
    s = s[0:length]
    self.cache = self.cache + s
    self.flush()

稍后我需要从输出文件中读取字符串。我使用Pythonstruct unpack模块如下:

   from struct import unpack
   key_length_bytes = 32
   key = ""
   for _ in range(0, key_length_bytes):
      carattere = chr(unpack('>B', in_file.read(1))[0])
      key = "%s%s" (key, carattere)

我明白了

key = "%s%s" (key, carattere)
TypeError: 'str' object is not callable

谢谢你的帮助。你知道吗


Tags: 文件key字符串inselfaddfordata

热门问题