Press "Enter" to skip to content

js对字符串的异或运算

Last updated on 2020年7月16日

首先 javascript 的异或运算是有位数限制的(二进制操作数超过32位时仅保留低位),参考MDN的定义Bitwise_XOR

所以超长字符运算时需要自定义异或运算,例如:

// 定义两个16进制的64位长字符,求异或结果
var a = '0b36bf0f61db95b7ad95c130dcfe5812c2c92a070afdf5579e374d4d443f8ec8';
var b = 'a7e2acedcba29cc0dabb5efa58babd28c0c1a138603c4f7ea8463706e479df9a';

代码实现:

// Note: implementation from crypto-js
// Convert a hex string to a byte array
function hexToBytes(hex) {
    hex = hex.toString();
    for (var bytes = [], c = 0; c < hex.length; c += 2)
    bytes.push(parseInt(hex.substr(c, 2), 16));
    return bytes;
}

// Convert a byte array to a hex string
function bytesToHex(bytes) {
    for (var hex = [], i = 0; i < bytes.length; i++) {
        var current = bytes[i] < 0 ? bytes[i] + 256 : bytes[i];
        hex.push((current >>> 4).toString(16));
        hex.push((current & 0xF).toString(16));
    }
    return hex.join("");
}

var x = hexToBytes(a);
var y = hexToBytes(b);
var z = new Array();
for(var i=0; i < x.length; i++){
    z.push(x[i] ^ y[i]);
}
console.log(bytesToHex(z));
// acd413e2aa790977772e9fca8444e53a02088b3f6ac1ba2936717a4ba0465152

参考:https://stackoverflow.com/questions/20566421/xor-of-two-hex-strings-in-javascript

发表评论

电子邮件地址不会被公开。 必填项已用*标注

Captcha Code

提示