2

我正在尝试将以下内容从 Java 移植到 JavaScript:

String key1 = "whatever";
String otherKey = "blah";
String key2;    
byte keyBytes[] = key1.getBytes();
for (int i = 0; i < keyBytes.length; i++) {
    keyBytes[i] ^= otherKey.charAt(i % otherKey.length());
}
key2 = new String(keyBytes);

这是我写的:

var key1 = "whatever";
var other_key = "blah";
var key2 = "";
for (var i = 0; i < key1.length; ++i)
{
    var ch = key1.charCodeAt(i);
    ch ^= other_key.charAt(i % other_key.length);
    key2 += String.fromCharCode(ch);
}

但是,他们给出了不同的答案......

有什么问题,JavaScript 字符串的编码方式不同,我该如何纠正它们?

4

1 回答 1

0

您在代码中忘记了一个 charCodeAt(),如下所示:

var key1 = "whatever";
var other_key = "blah";
var key2 = "";
for (var i = 0; i < key1.length; ++i)
{
    var ch = key1.charCodeAt(i);
    ch ^= other_key.charAt(i % other_key.length).charCodeAt(0);
    key2 += String.fromCharCode(ch);
}

在java中,在你做之前有一个隐式转换(char to byte)操作^=

我更改了代码以在 java 和 javascript 中查看该字节数组。运行后结果是一样的:

Javascript:

function convert(){
    var key1 = "whatever";
    var other_key = "blah";

    var key2 = "";
    var byteArray = new Array();

    for (var i = 0; i < key1.length; ++i){
       var ch = key1.charCodeAt(i);
       ch ^= other_key.charAt(i % other_key.length).charCodeAt(0);

       byteArray.push(ch);
       key2 += String.fromCharCode(ch);
    }

    alert(byteArray);
}

结果:21,4,0​​,28,7,26,4,26


爪哇:

static void convert() {
    String key1 = "whatever";
    String otherKey = "blah";
    String key2;
    byte keyBytes[] = key1.getBytes();
    for (int i = 0; i < keyBytes.length; i++) {
        keyBytes[i] ^= otherKey.charAt(i % otherKey.length());
    }
    System.out.println(Arrays.toString(keyBytes));
    key2 = new String(keyBytes);
}

结果:[21、4、0、28、7、26、4、26]

于 2014-09-05T19:06:38.073 回答