bitwise XOR in Javascript with a 64 bit integer

374 views Asked by At

I am looking for a way of performing a bitwise XOR on a 64 bit integer in JavaScript.

JavaScript will cast all of its double values into signed 32-bit integers to do the bitwise operations.

I already found this function in bitwise AND in Javascript with a 64 bit integer for bitwise AND and seems to work ok, but still need the XOR.

function and(v1, v2) {
    var hi = 0x80000000;
    var low = 0x7fffffff;
    var hi1 = ~~(v1 / hi);
    var hi2 = ~~(v2 / hi);
    var low1 = v1 & low;
    var low2 = v2 & low;
    var h = hi1 & hi2;
    var l = low1 & low2;
    return h*hi + l;
}

For the XOR Func this is the transformation i have done but is not working properly, any help modifying it would help me.

function XOR(v1, v2) {
    var hi = 0x80000000;
    var low = 0x7fffffff;
    var hi1 = ~~(v1 / hi);
    var hi2 = ~~(v2 / hi);
    var low1 = v1 ^ low;
    var low2 = v2 ^ low;
    var h = hi1 ^ hi2;
    var l = low1 ^ low2;
    return h * hi - l;
}

Any help is appreciated.

1

There are 1 answers

0
Jorge Lopez On

You have a mistakes in the lines

var low1 = v1 ^ low;
var low2 = v2 ^ low;

where it should be and & to recover the lower part of the number, and later perform the ^ xor operator in both sides

var low1 = v1 & low;
var low2 = v2 & low;

and the last line should be at the example with & operator a sum:

return h * hi + l;

Complete code above:

function XOR(v1, v2) {
    var hi = 0x80000000;
    var low = 0x7fffffff;
    var hi1 = ~~(v1 / hi);
    var hi2 = ~~(v2 / hi);
    var low1 = v1 & low;
    var low2 = v2 & low;
    var h = hi1 ^ hi2;
    var l = low1 ^ low2;
    return h * hi + l;
}

const res = XOR(114616149816979, 383577466862359);
console.log(res);