【问题标题】:How to convert integer numbers read from a text file and store as a binary file having 16bit integers?如何转换从文本文件中读取的整数并存储为具有 16 位整数的二进制文件?
【发布时间】:2019-09-09 19:01:17
【问题描述】:

尝试将文本文件中的十进制值转换为 16 位二进制并转换为二进制文件。

示例输入文件

120
300
-250
13
-120

代码:

def decimaltoBinary(filename,writefile):
    file = filename
    print(file)
    file_write = open(writefile,'wb')
    file_read = open(file, 'rb')
    for line in file_read:
        value = int(line)
        if value < 0:
            binary_value = bin((2**16) - abs(value))[2:].zfill(16)
            file_write.write(binary_value + "\n")
        else:
            binary_value = bin(int(value))[2:].zfill(16)
            file_write.write(binary_value + "\n")
    file_write.close()

decimaltoBinary(input_file.text,output_file.bin)

希望将转换后的十进制值写入二进制文件。非常感谢任何帮助

【问题讨论】:

  • 你的问题是?

标签: python python-3.x binary decimal


【解决方案1】:

您可以为此使用the struct module

data = [120,300,-250,13,-120] # you seem to have the reading part covered already
                              # using a list as data input for demo purposes
import struct

with open("f.bin","wb") as f: 
    for d in data:
        f.write(struct.pack('h', d)) # 2 byte integer aka short

with open("f.bin","rb") as f:
    print(f.read())  # b'x\x00,\x01\x06\xff\r\x00\x88\xff'

您只需要指定'h' 即可获得短(2 字节整数)打包。

对于怪异的打印输出责备 python - 它用 更短 普通字符替换“已知”\xXX 代码 - f.e. ',' =&gt; 0x2c\r => \x0d

【讨论】:

    猜你喜欢
    • 2022-01-16
    • 2013-08-22
    • 2016-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 1970-01-01
    相关资源
    最近更新 更多