Javascript Bitwise Operators

I stumbled across an interesting “edge” case in Javascript when porting gfx to Javascript.

Turns out Javascript converts numbers to 32-bit signed numbers before evaluating bitwise operators.  This is problematic because it prevents you from using the msb for 32-bit bitmaks:

Java:        0xaabbcc | 0xff000000 = 0xffaabbcc (4289379276)
Javascript:  0xaabbcc | 0xff000000 = 0xffabbcc  (-554434)

The workaround is pretty straightforward, you simply have to add 2^32+1 to convert back to an “unsigned” value:

var x = 0xaabbcc | 0xff000000;
if (x < 0) x += 0xffffffff+1;

But unfortunately, that means I have to wrap all bitwise operations in a method call, and perform that check, which I expect will not be anywhere near as fast as the straight operator call.

Comments are closed.