简体   繁体   中英

Javascript vs Java - String encoding

I'm trying to port the following from Java to 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);

Here's what I've written:

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);
}

However, they give different answers....

What's the catch, are JavaScript strings encoded differently and how can I rectify them?

You forgot one charCodeAt() on your code, as following:

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);
}

In java there is an implicit cast (char to byte) operation before you do ^=

I changed the code to see that byte array in java and javascript. After running the result was the same:

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);
}

result : 21,4,0,28,7,26,4,26


Java:

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);
}

result: [21, 4, 0, 28, 7, 26, 4, 26]

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