Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python / Javascript -- integer bitwise exclusive or problem

I'm proficient with both languages... but I'm having problems with the integer bitwise exclusive or logical operator. In javascript, it gives me one result, in python it gives me another..

Go ahead, open python and execute (-5270299) ^ 2825379669

Now with javascript, do the same calculation, and alert the result or whatever (example at http://thorat.org/OS/js.php)

The results are different! I have no idea why!

I MUST be missing something.

like image 345
Nikhil Avatar asked Dec 21 '22 19:12

Nikhil


2 Answers

JavaScript's integers are 32-bit whereas Python automatically converts to the unlimited length long format when values exceed 32 bits. If you explicitly force Python not to sign extend past 32 bits, or if you truncate the result to 32 bits, then the results are the same:

>>> (-5270299 & 0xFFFFFFFF) ^ 2825379669
1472744368L
>>> (-5270299 ^ 2825379669) & 0xFFFFFFFF
1472744368L
like image 123
John Kugelman Avatar answered Dec 31 '22 13:12

John Kugelman


2825379669 does not fit into 32 bits.

All numbers in JavaScript are 64 bit floats, but when doing bitwise operations on them, they get converted to 32 bit integers first, then the bitwise operation is performed, and afterwards they get converted back to a 64 bit float.

Python on the other hand happily handles long values (more than 32 bits) for integers.

So if you want the same result in JavaScript, you'll have to do some tricks, like storing your 64 bit integer in two JavaScript numbers and then do the operations on those two. Which will be even slower than the already horrible slow built in conversion of float to int and back.

like image 26
Ivo Wetzel Avatar answered Dec 31 '22 13:12

Ivo Wetzel