python以十六进制写入文件,将十六进制数据写入文件

I'm trying to write hex data taken from ascii file to a newly created binary file

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

my code

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))

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

final output: 0x9f0x2c0x380x590xcd0x110x7c0x590xc90x30xea0x37 which is wrong!

where is the issue?

解决方案>>> 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()))

)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值