Home > Net >  Why do I get negative value when `or` a large number in nodejs?
Why do I get negative value when `or` a large number in nodejs?

Time:08-25

I am using nodejs 16 and I have below code:

> a=Math.pow(2, 31)
2147483648
> a|a
-2147483648

As you can see the result of a|a is negative value. I expect to be the same value as a. But why it gives me negative value? What can I do to get the original value?

CodePudding user response:

What's happening here is pretty well explained on LinuxHint's JavaScript Bitwise Operators

In JavaScript numbers are stored as 64 bits; however, all bitwise operations are worked on binary numbers with 32 bits. Therefore, JavaScript converts numbers into 32 bits before the implementation of bitwise operators. After the implementation of bitwise operators, the numbers are converted back into 64 bits.

That's why the problem is present for Math.pow(2, 31) or higher numbers.

Normally, you would expect that an integer a is equal to a | a, but due to the reason above, this is not the case.

const orMatchesSelf = (a) => console.log(a == (a | a));

orMatchesSelf(1) // true 
orMatchesSelf(12314) // true
orMatchesSelf(Math.pow(2, 31) -1 ) // true
orMatchesSelf(Math.pow(2, 31)) // false
  • Related