Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why returns different value when use & operator in JavaScript and C#?

Tags:

javascript

c#

I have worked the same process in JavaScript and C# with the & operator, but the result was different.

C# Code

Int64 x = (634586400000000000 & 4611686018427387903);
x= 634586400000000000;

JavaScript Code

var x = (634586400000000000 & 4611686018427387903);
x= 0;

Any ideas?

like image 897
developerone Avatar asked Aug 05 '11 09:08

developerone


2 Answers

Bitwise operators in javascript convert the operands to signed 32-bit integers (from the native IEEE 754 floats numbers are stored in).

like image 91
Alex K. Avatar answered Nov 05 '22 20:11

Alex K.


It looks to me like you're exceeding JavaScript's maximum integer value. The maximum supported value for JavaScript integers is spec'd at 2^53.

UPDATE:

My initial response here wasn't correct - the issue is not JavaScript's max integer value, it's the max value of each operand handled by the ampersand op:

var biggest = 4294967291; // maximum 32 bit unsigned integer
alert(biggest & 1); // alerts 1
alert((biggest + 1) & 1); // alerts 0

Happy coding!

B

like image 43
Brian Avatar answered Nov 05 '22 21:11

Brian