Reputation: 3523
I want to read a file character by character and XOR each byte with 172
, then save as a new file.
I've made the following:
b = bytearray(open('in.txt', 'rb').read())
for i in range(len(b)):
b[i] ^= 0xAC # XOR byte with 172
open('out.txt', 'wb').write(b)
Trying it on a sample text file:
ïÃÂËÞÍØÙÀÍØÅÃÂß
I end up with garbage:
oo/o.o'o2o!o4o5o,o!o4o)o/o.o3
The expected output is instead:
Congratulations
Doing this by hand, I get an expected output:
str(chr(0xEF ^ 0xAC)) # 'C', 'ï' XOR 172 = 67, 67 to ASCII is 'C'
str(chr(0xC3 ^ 0xAC)) # 'o'
str(chr(0xC2 ^ 0xAC)) # 'n'
...
But trying to automate it generates nonsense. Why doesn't it correctly work and how can I get my expected output?
Upvotes: 0
Views: 301
Reputation: 8982
Your file in.txt
doesn't use single-byte character encoding Windows-1254 as you expect but perhaps multibyte UTF-8 encoding.
Upvotes: 2