Friday, June 21, 2013

JavaScript convert signed integer to unsigned integer or Int32 to UInt32

Try this in your browser:

    document.write((1 << 31));

What do you get? Is it -2147483648?

So, why is it negative? The reason for this is that JavaScript Bitwise Operators convert your number into 32 bit signed integer. 

The trick and absolutely the simplest and fastest to flip between int32 and uint32 is to use zero-fill right shift like this:

    document.write((1 << 31) >>> 0);

Voila! This time you'll get 2147483648? Simple? Keep in mind that doing >>>0 again will flip uint32 back to int32.