为什么文件中的位数不同并且同一文件的二进制表示形式?

问题描述 投票:1回答:1

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

注意,文件的byte_obj中的字节对象数为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个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.