2012-02-11 27 views
12

我正在將加密函數從PHP轉換爲JS。JavaScript - 在字符串上按位異或?

PHP:(兩個$ y和$ z是ASCII字符,因此$ x是固有的ASCII古怪。)

$x = ($y^$z); 

否則在JS導致$ x = 0的

相同我試過:

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

但它得到了不同的結果。

回答

21

您不需要將其轉換回字符串。按位運算符處理數字。 1^3 相同1^11 相同1^10

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

謝謝!那樣做了。 – 2012-02-11 03:08:15

9

toString(2)轉換爲二進制字符串,但你要的數量型工作。

只需刪除toString(2)部分,它應該工作。