3

I am trying to do bitwise AND operation on long numbers in Javascript.

I have tried both the solution given at (How to do bitwise AND in javascript on variables that are longer than 32 bit?) but none of it was accurate with the numbers I am working with. I have created a plunker for the same to demonstrate the issue.

Plunkerhttp://plnkr.co/edit/awFGFKxpkmwIPpnJ06lu?p=preview

Any suggestion/help will be of great help.

Community
  • 1
  • 1
Jimit Joshi
  • 435
  • 1
  • 4
  • 10

2 Answers2

5

JavaScript numbers are 64-bit floating point values. The format is such that integers requiring more than 53 bits cannot be represented exactly. There's no way around that problem without the assistance of a library that provides a complete alternative number representation. Once a value expressed as a numeric constant in source code is turned into a number when the program runs, it's already too late.

Your sample code involves a number that requires 60 bits. That means the low 7 bits (or so; it's a little more complicated than that) are gone, so the AND operation with 8 turns up zero.

Pointy
  • 405,095
  • 59
  • 585
  • 614
2

I found a library which is giving correct result of Long numbers. It's Long.js.

Found it from Performing bitwise operations on large values

I have browserify the library to use it in angular directly. The plunker is also updated with browerify JS and correct ans in Result2 textbox.

Plunkerhttp://plnkr.co/edit/awFGFKxpkmwIPpnJ06lu?p=preview

-Jimit

Community
  • 1
  • 1
Jimit Joshi
  • 435
  • 1
  • 4
  • 10