简体   繁体   中英

JavaScript - Bitwise XOR on strings?

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.

You don't need to convert it back to a string. Bitwise operators work on numbers. 1 ^ 3 10 is the same as 1 ^ 11 2 is the same as 1 ^ 10 3 .

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

The toString(2) converts to a binary String , but you want to work on the Number type.

Simply drop the toString(2) part and it should work.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM