What is the Javascript’s highest value that can be safely used in a bitmask?

Let’s say I want to create a bitmask in Javascript. I would toggle a bit on like this:

mask |= (1 << bit);

clear a bit like this:

mask &= ~(1 << bit);

and check if a bit is set like this:

(bit & mask) != 0

My question is, what is the safest amount of bits that this works on in Javascript? I have three main guesses:

  1. 32 bits, as bit operations may be undefined past 32 bits
  2. 53 bits, as Number.MAX_SAFE_INTEGER is 2^53 - 1
  3. 64 bits, as Javascript uses 64 bits for each number

Which one is correct? Or is it something else?

Answer

32 bits:

Bitwise operators treat their operands as a set of 32 bits (zeros and ones) and return standard JavaScript numerical values.

Specification:

6.1.6.1.9 Number::leftShift ( x, y )

  1. Let lnum be ! ToInt32(x).
  2. Let rnum be ! ToUint32(y).
  3. Let shiftCount be the result of masking out all but the least significant 5 bits of rnum, that is, compute rnum & 0x1F.
  4. Return the result of left shifting lnum by shiftCount bits. The result is a signed 32-bit integer.

Leave a Reply

Your email address will not be published. Required fields are marked *