【问题标题】:How to convert a lot of data from binary file to string of ones and zeros fast如何快速将大量数据从二进制文件转换为 1 和 0 字符串
【发布时间】:2019-10-10 22:17:41
【问题描述】:

我尝试将二进制文件中的数据转换为 1 和 0 字符串。 二进制文件的大小约为2MB,这需要很多时间来转换它,我怎样才能使它更快

我试图通过将字节转换为 int 并从那里转换为字符串来将过程分割成碎片

def bytes_to_string(self, xbytes):
    intermediate_result = int.from_bytes(xbytes, byteorder='big')
    return intermediate_result


def dec_to_bin(self,x):
    return int(bin(x)[2:])

##
## bin_code is where the data from the binary file is stored

bin_code = str(self.dec_to_bin(self.bytes_to_string(bin_code)))

【问题讨论】:

  • str(int(xbytes, 2)) 可能会有所帮助
  • 我尝试使用它,但它不起作用,它返回:ValueError: invalid literal for int() with base 2
  • 我认为您需要为您的 xbytes 提供示例,因为也很少需要输入
  • 你是对的,但它太长而且它是十六进制的,我不能在这里打印它
  • 是连字符吗?

标签: python string binaryfiles converters


【解决方案1】:

我的解决方案是:

"".join([format(ord(byte), "08b") for byte in bytes])

虽然,我不知道它有多快。

【讨论】:

    猜你喜欢
    • 2016-01-01
    • 2017-07-12
    • 1970-01-01
    • 2017-03-02
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 2021-08-11
    相关资源
    最近更新 更多