【问题标题】:Why the Number of Bits is Different in File and The Binary Representation of the same File?为什么文件的位数和同一个文件的二进制表示不同?
【发布时间】:2020-03-22 23:59:13
【问题描述】:

我编写了一个代码(在帖子末尾给出),它只是将文件的字节(=byte_obj)转换为二进制数binary_dt,所以我希望byte_obj 中的位数和binary_dt 相同,但事实并非如此,我使用了一个 3 KB 的文本文件并得到了 17 KB 文件的输出(输出 = 将binary_dt写入文本文件),这是为什么呢?

注意,文件byte_obj中的byte-object的个数是2117,byte_obj的大小(由于结构数据,会比实际内容有开销)是2150,所以差别不大这里..

那么,有什么问题可以请任何人解释吗?如果我想从binary_dtbyte_obj 中获得相同数量的位数,我该怎么办?

import sys

input_file="a.txt";output_file="b.txt"
with open(input_file, "rb") as file: #--> open file in binary read mode
  byte_obj = file.read() #--> read all binary data


print("Number of byte-object in 'byte_obj' = ",len(byte_obj))
print("The size of 'byte_obj' (has an overhead over the actual content, due to structure data) = \n",str(sys.getsizeof( byte_obj))) #Return the size of an object in bytes.


binary_dt=bin(int.from_bytes( byte_obj, byteorder=sys.byteorder))

print("The number of bits in 'binary_dt' on PC= \n",len(binary_dt)) #Return the size of an object in bytes.
print("binary_dt: \n",binary_dt)

text_file = open(output_file, "w")
n = text_file.write(binary_dt)
text_file.close()

【问题讨论】:

    标签: python python-3.x memory binaryfiles binary-data


    【解决方案1】:

    这是因为您正在读取二进制并写入 ASCII:

    >>> bin(3)
    '0b11'
    

    这里是 2 位转换成 4 字节。

    【讨论】:

    • 我是新手,请您告诉我如何读写二进制文件?我需要什么功能?请注意,我需要这些字节的二进制字符串,即,我需要该文件中的二进制字符串。
    • @MikeSQ 您应该在您的问题中添加程序的预期和实际输出以及输入。最好是尽可能小的文件——不要使用 17kb 的文件,从小文件开始,比如 5-6 字节。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-25
    • 2021-01-08
    • 2020-10-16
    • 1970-01-01
    • 2015-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多