-1

I need to do bitwise operations on large numbers.

For example:

2 | 2147483648

I would expect 2147483650, but instead, get -2147483646

Why is this, and what can I do about it?

Note, the code I am working on is some old javascript code that is run server side in classic asp, which I believe is an older version of js

GWR
  • 1,878
  • 4
  • 26
  • 44
  • 4
    [MDN bitwise operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators) You have a 32 bit limitation with JS bitwise operators. –  Dec 27 '16 at 14:51
  • 1
    @hindmost why would you guess that? op - you're getting an int overflow I believe (or so it seems I don't know much about bit manipulations in js) – user2717954 Dec 27 '16 at 14:51
  • See [this SO article](http://stackoverflow.com/questions/2983206/bitwise-and-in-javascript-with-a-64-bit-integer#2983294) for a good explanation and a decent work around. If you need to perform bit-wise operations on 64 bit values consider using two 32-bit values. – RamblinRose Dec 27 '16 at 15:27
  • VBScript does signed integers only (which we call longs). It doesn't matter as the bits are the same. You just have to be aware it will be shown as a negative number. Just don't do basic maths on them. –  Dec 27 '16 at 21:24
  • You are incorrect. On values like those in the question, VBScript throws an overflow error: Response.Write (2 and 2147483648) - Overflow: '[number: 2147483648]' – GWR Dec 28 '16 at 11:00

1 Answers1

1

I found a workaround.

You can use the BigInteger.js library with slight modifications for use in server-side JS with Classic ASP.

https://raw.githubusercontent.com/peterolson/BigInteger.js/master/BigInteger.js

For use in classic asp, do the following:

Modify line 21 and 28 of the BigInteger.js library so it will work server side with classic ASP:

Change Line 21:

BigInteger.prototype = Object.create(Integer.prototype);

To:

BigInteger.prototype = new Object(Integer.prototype);

And make the same change to line 28.

Then, remove the last 4 lines. They are not needed:

// Node.js check
if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
    module.exports = bigInt;
}

Then in your script include it like this:

<script language="javascript" runat="server">

... the bigInteger.js code... 

function bitOrJS(a, b) {
    var big = new bigInt(a);

    return big.or(b);

}
</script>

You can now use the function in the classic ASP vbscript code:

Dim result

result = bitOrJS(2147483648, 2)

response.write result

Output will be 2147483650 as expected.

GWR
  • 1,878
  • 4
  • 26
  • 44