I'm trying to convert a text file to hexadecimal and then back to a text again. It works well as long as I do not use new line.
The first function take te filename and returns a list with integers that represents each letter.
block = []
file = open(filename, 'rb')
content = file.read()
hexstring = binascii.hexlify(content)
for i in range(0,len(hexstring),2):
block.append(int(hexstring[i:i+2], base=16))
return block
This is how I convert back to plaintext.
for i in range(len(stringList)):
tmp = stringList[i]
for j in range(len(tmp)):
hexString = str(hex(tmp[j]))
hexString = hexString.replace('0x', '')
pt = bytearray.fromhex(hexString).decode()
plainText.append(pt)
The code is awful but works as long as I do not have a new line. Then I get the following error.
pt = bytearray.fromhex(hexString).decode()
ValueError: non-hexadecimal number found in fromhex() arg at position 1
try using codecs modules
import codecs def encode(): with open(file='sample.txt') as file: text = file.read() return codecs.encode(bytes(text, encoding='utf-8'), "hex") def decode(encodedString): return codecs.decode(encodedString, 'hex') a = encode() b = decode(a) print(a) print(b)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.