JavaScript - 字符串上的按位异或?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9237236/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript - Bitwise XOR on strings?
提问by Silviu-Marian
I'm translating an encryption function from PHP to JS.
我正在将加密函数从 PHP 翻译成 JS。
PHP: (Both $y and $z are ASCII characters, so $x is inherently an ASCII oddity.)
PHP:($y 和 $z 都是 ASCII 字符,所以 $x 本质上是一个 ASCII 奇数。)
$x = ($y ^ $z);
Doing the same in JS results in $x = 0.
在 JS 中做同样的事情会导致 $x = 0。
I tried:
我试过:
$x = String.fromCharCode(($y).charCodeAt(0).toString(2) ^ ($z).charCodeAt(0).toString(2));
But it gets to a different result.
但它得到了不同的结果。
回答by zzzzBov
You don't need to convert it back to a string. Bitwise operators work on numbers. 1 ^ 3
10is the same as 1 ^ 11
2is the same as 1 ^ 10
3.
您不需要将其转换回字符串。按位运算符处理数字。1 ^ 3
10与1 ^ 11
2相同 与1 ^ 10
3相同。
//this should work for single characters.
x = String.fromCharCode(y.charCodeAt(0) ^ z.charCodeAt(0));
回答by copy
The toString(2)
converts to a binary String, but you want to work on the Number type.
该toString(2)
二进制转换字符串,但你想对数字类型的工作。
Simply drop the toString(2)
part and it should work.
只需放下toString(2)
零件,它就可以工作。