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.

1 comment:

  1. Unfortunately, the >>> operator is limited to 32-bits only, so the following:

    0x100000000 >>> 0

    returns 0, because the 1 is outside the 32-bit limit.

    Note that Javascript's max integer size is 0x20000000000000, so the above example is comfortably within the limit under normal circumstances