What is the maximum integer it is safe to use in a Javascript bitmask flag value?

797 views Asked by At

This is mostly just a sanity-check.

Mozilla says that

The operands of all bitwise operators are converted to signed 32-bit integers in two's complement format.

and that

The numbers -2147483648 and 2147483647 are the minimum and the maximum integers representable through a 32bit signed number.

Since 2147483647 is 0x7FFFFFFF, I believe that 0x40000000 (that is to say, not 0x80000000) is the maximum number I can safely use as a javascript flag value. But I'd like to make sure I haven't missed something or that there aren't other gotchas. Thank you in advance!

1

There are 1 answers

2
AudioBubble On BEST ANSWER

The value range is a complete 32-bit value, ie. 0 to 0xffffffff (or 232-1). If it will be signed or not depends. If it will be signed initially then this will produce -1:

document.write(0xffffffff>>0);

But you can use unsigned values too which means the range is [0, 4294967295]:

document.write(0xffffffff>>>0);

The number 0x40000000 is only gonna give you half your range (in the negative range, in the positive it would be 0x40000000-1, or 0x3fffffff) so this is not the safe number for a 32-bit signed range.

You safe-range for signed number would be [0x80000000, 0x7fffffff], so the common safe-margin mask would be 0x7fffffff, however, you would need to preserve the sign-bit:

number = number < 0 ? number & 0xffffffff : 0x7fffffff;

And for unsigned your mask would always be 0xffffffff.