原文:http://blog.youkuaiyun.com/emaste_r/article/details/13275529
问题描述:python以16进制读取文本,就是获取以下图片红框中的DF,F8,DF这些16进制,然后做一些处理,再写到文件中。
1个字节 == 8Bit == 两个hex(1~F)
文件读取可以按行readline。。
- f = open('1.txt','rb')
- while True:
- t = f.readline()
- if not t :
- break
- f.close()
str转成hexs[]:
- hexs = []
- for ss in s:
- tmp = (hex(ord(ss)).replace('0x',''))
- if len(tmp) == 2:#DF之类的
- hexs.append(tmp)
- else:#0D之类的,默认写成D
- hexs.append('0'+tmp)
hexs[]转成真正的16进制数据:
其实到这里一想,python内部的数字表示一定都是2进制啊,我用16进制最终写入文件的是二进制,用10进制最终写入文件的也依旧是二进制。那么,思路是直接把hexs转成10进制,反正计算机内部一定把它当成2进制了。
- arr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
- arr2 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
- def tran(r):#把0~F转成数字
- for i in range(len(arr)):
- if r == arr[i]:
- return arr2[i]
- res = []
- for i in range(len(hexs)):
- a = tran(hexs[i][0])*16+tran(hexs[i][1])
- res.append(a)
10进制转成2进制,文件open的时候,带上'b'参数
Ps:别忘了import strcut
- ff = open('out.txt','wb')
- for i in res:
- B = struct.pack('B',i)
- ff.write(B)
- ff.close()
如此一来就写入文件成功,思路到这里就完成了。
对两个文件的xor处理
- # -*- coding: cp936 -*-
- import binascii
- import struct
- #每个字节转成hex,0x顺便去掉,对于不足两位的补0
- def str2hex(str):
- hexs = []
- for s in str:
- tmp = (hex(ord(s)).replace('0x',''))
- if len(tmp) == 2:
- hexs.append(tmp)
- else:
- hexs.append('0'+tmp)
- return hexs
- arr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']
- arr2 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
- def tran(r):
- for i in range(len(arr)):
- if r == arr[i]:
- return arr2[i]
- f = open('1.txt','rb')
- f2 = open('2.jpg','rb')
- hexs = []
- hexs2 = []
- while True:
- t = f.readline()
- t2 = f2.readline()
- if not t or not t2:
- break
- hexs.extend(str2hex(t))
- hexs2.extend(str2hex(t2))
- f.close()
- f2.close()
- ff = open('out.txt','wb')
- for i in range(min(len(hexs),len(hexs2))):
- a = tran(hexs[i][0])*16+tran(hexs[i][1])
- b = tran(hexs2[i][0])*16+tran(hexs2[i][1])
- B = struct.pack('B',a^b)
- ff.write(B)
- ff.close()