0

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
    JavaScript numbers don’t have 64-bit precision. Are you aware of that? You might want an array of `[high, low]` 32-bit integers instead, which are also more straightforward to work with. (Or a `BigInt`, if performance isn’t a concern.) – Ry- Jun 14 '22 at 22:24
  • 1
    Use a `BigInt`. – Bergi Jun 14 '22 at 22:43
  • The `and` implementation seems quite understandable. Please show us your attempt at transforming the code into an `or` implementation. Hint: you need to change only five characters! – Bergi Jun 14 '22 at 22:43
  • Please link the source *where* you found that `and` function if you didn't write it yourself. – Bergi Jun 14 '22 at 22:45
  • You changed 8 characters in your attempt. 5 of them would've been enough. – Bergi Jun 14 '22 at 23:03
  • Do you understand what each line in the code does? Can you try to explain them, please? – Bergi Jun 14 '22 at 23:05
  • I dont understand all of it, but thats all i have, if you can explain it to me and point me to the right direction, its great with me. – José A Pérez Jun 14 '22 at 23:09

0 Answers0