将十六进制数据写入文件

编程入门 行业动态 更新时间:2024-10-27 00:27:14
本文介绍了将十六进制数据写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将从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())) )

更多推荐

将十六进制数据写入文件

本文发布于:2023-10-27 18:31:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1534187.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   数据   将十六进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!