Tim
Tim

Reputation: 2411

Python XOR operator on hex values

I'm trying to figure out how take the XOR of every byte in my string:

string = "\xa3\xb4\x55"

with 100000 (binary). How would I do this in python? I've tried doing this:

newString = ""
for n in string:
    new = n ^ 0x20
    newString.append(new)

I need the output of newString to look like

output = "\x83\x94\x75"

but i'm currently not getting that :-( any help would be appreciated! Thank you!

Upvotes: 1

Views: 285

Answers (2)

Luke Briggs
Luke Briggs

Reputation: 3789

You'll need to convert each character to its charcode, then perform the xor on the charcodes. After that you then convert the result back to a character, which results in something like this:

string = "\xa3\xb4\x55"

newString = ""
for n in string:
    new = chr(ord(n) ^ 0x20)
    newString += new

print(newString)

Here's a working example

Upvotes: 1

UltraInstinct
UltraInstinct

Reputation: 44464

You need to convert to number using ord(..) and then back to a character using chr(..).

>>> "".join(chr(ord(x) ^ 0x20) for x in "\xa3\xb4\x55")
'\x83\x94u' # 'u' => '\x75'

Upvotes: 1

Related Questions