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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 06:02:04  来源:igfitidea点击:

JavaScript - Bitwise XOR on strings?

javascriptencryptionxor

提问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 ^ 310is the same as 1 ^ 112is the same as 1 ^ 103.

您不需要将其转换回字符串。按位运算符处理数字。1 ^ 3101 ^ 112相同 与1 ^ 103相同。

//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)零件,它就可以工作。