将十六进制数据写入文件 [英] Writing hex data into a file
本文介绍了将十六进制数据写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试将从ascii文件获取的十六进制数据写入新创建的二进制文件
I'm trying to write hex data taken from ascii file to a newly created binary file
ascii文件示例:
ascii file example:
98 af b7 93 bb 03 bf 8e ae 16 bf 2e 52 43 8b df
4f 4e 5a e4 26 3f ca f7 b1 ab 93 4f 20 bf 0a bf
82 2c dd c5 38 70 17 a0 00 fd 3b fe 3d 53 fc 3b
28 c1 ff 9e a9 28 29 c1 94 d4 54 d4 d4 ff 7b 40
我的代码
hexList = []
with open('hexFile.txt', 'r') as hexData:
line=hexData.readline()
while line != '':
line = line.rstrip()
lineHex = line.split(' ')
for i in lineHex:
hexList.append(int(i, 16))
line = hexData.readline()
with open('test', 'wb') as f:
for i in hexList:
f.write(hex(i))
认为hexList
已保存已十六进制转换的数据,并且f.write(hex(i))
应该将这些十六进制数据写入文件,但是python使用ascii模式将其写入
Thought hexList
holds already hex converted data and f.write(hex(i))
should write these hex data into a file, but python writes it with ascii mode
最终输出:0x9f0x2c0x380x590xcd0x110x7c0x590xc90x30xea0x37
这是错误的!
final output: 0x9f0x2c0x380x590xcd0x110x7c0x590xc90x30xea0x37
which is wrong!
问题出在哪里?
推荐答案
使用 binascii.unhexlify
:
>>> import binascii
>>> binascii.unhexlify('9f')
'\x9f'
>>> hex(int('9f', 16))
'0x9f'
import binascii
with open('hexFile.txt') as f, open('test', 'wb') as fout:
for line in f:
fout.write(
binascii.unhexlify(''.join(line.split()))
)
这篇关于将十六进制数据写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文