I am doing an assignment to decipher a one-time-pad code (7 sentences, repeated keys for each character position among all 7 sentences). I'm solving it by guess work and I need to XOR the binary value of my guess letter with the binary value of the cypher character in order to get a key.
However, I cannot XOR the binary values returned by Python as they are in string format. I cannot convert them to integers since I need the '0b' part, but I also cannot XOR it because it's a string.
Any suggestions as to how to work around this?
Integers in Python support binary bitwise operations; the binary bitwise operators take integer operands and produce new integers with the bits altered, just like they would in C code.
Convert your string (presumably you have something like 0b1001101
) to integer, use the ^
XOR operator on that. If you need string output at the end, you can always use bin()
again on the integer:
>>> bin(102)
'0b1100110'
>>> 102 ^ 255
153
>>> bin(102 ^ 255)
'0b10011001'
If you have ASCII bytes (characters in Python 2 strings are bytes), use ord()
to get an integer representation, chr()
to go back to a byte (character) again.
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.