【问题标题】:Change string to binary then write it to a file将字符串更改为二进制,然后将其写入文件
【发布时间】:2019-07-24 01:33:41
【问题描述】:

目前我必须将一串二进制文件写入文件 --- 但是,我需要将其写入二进制文件。例如,我得到了字符串 s = "1011001010111"。我希望能够以二进制格式将其写入文件。因此,当我进行 hexdump 时,文件将具有以下二进制输出:1011001010111。我曾考虑逐个字符地遍历我的字符串以获得哪个位值,但是我在以二进制格式将其写出时遇到问题文件。

编辑:我的代码

bits2 = "000111010001110100011110000111110101"
int_value = int(bits[1::], base=2)
bin_array = struct.pack('i', int_value)
f = open("test.bnr", "wb")
f.write(bin_array)

【问题讨论】:

  • 您能否展示您当前拥有的代码以及为什么它没有按预期工作?
  • 添加了代码...
  • 什么都不对。请检查您的代码并上传正确的代码。作为第一件事,您声明了变量 bits2 和 int int() 函数,您使用了未声明的 bits 变量。您忘记导入结构库的第二件事。修复前一点的第三件事,struct.pack() 将永远无法正确完成,因为:'i' format requires -2147483648 <= number <= 2147483647
  • @Zoralikecury 如果答案对您有帮助,请删除以投票。

标签: python-2.7 file binary


【解决方案1】:

因为您的答案有点混乱,我将其用作示例字符串:"1011001010111"

这是将字符串写入二进制文件的代码。

import struct 

bits = "1011001010111"
int_value = int(bits,2) # Convert the string to integer with base 2
bin_array = struct.pack('>i', int_value) # Pack the int value using a big-endian integer

with open("test.bnr", "wb") as f: # open the file in binary write mode
    f.write(bin_array) # write to the file

根据struct模块的documentation可以看出你需要>i。 p>

您有两种不同的方式来转储文件,使用 unix 终端:

hexdump -e '2/1 "%02x"' test.bnr

但是这里你会得到十六进制数,后面需要转换一下。

或者你可以使用这个脚本来读取文件并打印出二进制字符串。

with open('test.bnr', 'rb') as f:
    for chunk in iter(lambda: f.read(32), b''):
        print str(bin(int(chunk.encode('hex'),16)))[2:]

正如您使用字符串 "1011001010111" 的问题所预期的那样,您会收到从文件中读取的相同字符串。

使用第二个字符串 ("000111010001110100011110000111110101") 你会得到一个错误:

'i' format requires -2147483648 <= number <= 2147483647

这是因为 'i' 选项对于这个数字不正确。 将此值转换为 int 您会收到 7815160309。这个数字对于整数来说太大了。

这里你需要使用'>Q'或'>q'。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2010-12-08
    • 2022-10-05
    • 2021-10-27
    • 2016-01-15
    • 2012-09-22
    • 2016-10-03
    相关资源
    最近更新 更多