Unsigned Integer in Javascript

document.write( (1 << 31) +"<br/>");

The << operator is defined as working on signed 32-bit integers (converted from the native Number storage of double-precision float). So 1<<31 must result in a negative number.

The only JavaScript operator that works using unsigned 32-bit integers is >>>. You can exploit this to convert a signed-integer-in-Number you’ve been working on with the other bitwise operators to an unsigned-integer-in-Number:

document.write(( (1<<31)>>>0 )+'<br />');

Meanwhile:

document.write( (1 << 32) +"<br/>");

won’t work because all shift operations use only the lowest 5 bits of shift (in JavaScript and other C-like languages too). <<32 is equal to <<0, ie. no change.

Leave a Comment