如何将单个十六进制值写入 Python 中的文件?
How to write a single hex value to file in Python?
我正在尝试写入一个十六进制值,比如 'F' 到文件:
a = int('F', 16)
f.write(chr(a))
但是,此代码段为我提供了带有 0F
的文件。我只想要文件中的单个十六进制 F
。我知道这是因为一个char是由一个字节表示的,有没有办法不用pad直接写十六进制值?
f.write("{:X}".format(a))
它会写成F
:
>>> "{:X}".format(a)
'F'
您可以使用struct
模块将原始数据写入文件。这将向文件写入一个字节
open('file','wb').write(struct.pack('b', 0xf))
大多数现代操作系统都无法执行您尝试执行的操作。通用计算平台可以处理的最小数据单元是一个字节。
查看此 wiki article 了解更多详细信息,其中指出:
"Historically, the byte was the number of bits used to encode a single character of text in a computer and for this reason it is the smallest addressable unit of memory in many computer architectures. "
我正在尝试写入一个十六进制值,比如 'F' 到文件:
a = int('F', 16)
f.write(chr(a))
但是,此代码段为我提供了带有 0F
的文件。我只想要文件中的单个十六进制 F
。我知道这是因为一个char是由一个字节表示的,有没有办法不用pad直接写十六进制值?
f.write("{:X}".format(a))
它会写成F
:
>>> "{:X}".format(a)
'F'
您可以使用struct
模块将原始数据写入文件。这将向文件写入一个字节
open('file','wb').write(struct.pack('b', 0xf))
大多数现代操作系统都无法执行您尝试执行的操作。通用计算平台可以处理的最小数据单元是一个字节。
查看此 wiki article 了解更多详细信息,其中指出: "Historically, the byte was the number of bits used to encode a single character of text in a computer and for this reason it is the smallest addressable unit of memory in many computer architectures. "