BitwiseOR does not return the correct value

Why bittUOR ( |) returns 1410065407when it should be == a && bin the following case - given that javascript precision intis accurate to 15 numbers?

let a = 9999999999; // 10d
let b = 9999999999; // 10d
let c = a | b;
let d = b | a;

console.log({a,b,c,d});

// example 2

let a2 = 999999999; // 9d
let b2 = 999999999; // 9d
let c2 = a2 | b2;
let d2 = b2 | a2;

console.log({a2,b2,c2,d2});
Run codeHide result
+4
source share
1 answer

[...] given that javascript int precision is accurate to 15 numbers

Not numbers, but 32 bits.

The value of 9.999.999.999 is higher than the full 32-bit range, that is 4,294,967,296 (or 2 ^ 32), so what happens is that you "convert" (clamp) the number to 32 bits, which will happen with any bitwise quotes:

console.log(9999999999>>0);
console.log(9999999999&0xffffffff);
console.log(9999999999<<0);
console.log(9999999999|9999999999);
// etc.
Run codeHide result

So what happens is that 1) the number is clamped to the 32-bit range, i.e. 1,410,065,407 in this case:

Full range would require 34-bits:
  1001010100000010111110001111111111 -> 9,999,999,999

Actual result, max 32-bits:
  --01010100000010111110001111111111 -> 1,410,065,407

then 2) OR'ed , , .

999,999,999 32- , .

+5

Source: https://habr.com/ru/post/1691087/


All Articles