Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

162
Views
Why do I get negative value when `or` a large number in nodejs?

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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!