JavaScript - Bitwise XOR on strings?

Silviu-Marian picture Silviu-Marian · Feb 11, 2012 · Viewed 19.9k times · Source

I'm translating an encryption function from PHP to JS.

PHP: (Both $y and $z are ASCII characters, so $x is inherently an ASCII oddity.)

 $x = ($y ^ $z);

Doing the same in JS results in $x = 0.

I tried:

 $x = String.fromCharCode(($y).charCodeAt(0).toString(2) ^ ($z).charCodeAt(0).toString(2));

But it gets to a different result.

Answer

zzzzBov picture zzzzBov · Feb 11, 2012

You don't need to convert it back to a string. Bitwise operators work on numbers. 1 ^ 310 is the same as 1 ^ 112 is the same as 1 ^ 103.

//this should work for single characters.
x = String.fromCharCode(y.charCodeAt(0) ^ z.charCodeAt(0));