How do JS bitwise operations work if `number` is not stored as an integer?

Viewed 114

According to this, a JavaScript number is stored as a floating point value. Isn't then an integer value also broken up into its characteristic and mantissa parts? If so, how do bitwise operators work? 100 >>1 correctly gives 50. ~2 correctly gives -3 (2's complement).

I just realize I have a 5-year old application using "bit masking". Basically I was using a 16-bit pattern to have each bit represent a different permissions role. So, values used are from 0 to 65535. It has been working fine thus far. I wonder if I need to fix that first.

1 Answers

The JavaScript implementation converts each floating-point representation to a 32-bit integer and applies the bitwise operator.

JavaScript is an implementation of ECMAScript. ECMAScript 2020 Language Specification describes the two-operand bitwise operations in clause 6.1.6.1.16, where it shows that each operand is converted to an integer with the ToInt32 function. (This is an abstract operation in the specification, not necessarily an actual function in the implementation.) Clause 7.1.6 describes the ToInt32 operation. For infinities, it returns zero. Otherwise, it effectively discards the fraction part and returns the low 32 bits of the signed integer part (treating them as two’s complement).

The single-operand ~ operator is discussed separately, in 6.1.6.1.2, but also applies ToInt32 to its operand.

Two Notes About the ECMAScript specification

That link is generic; in the future it may be updated to later versions rather than the 2020 version.

The unusual “!” and “?” in the operation descriptions are described in clause 5.2.3.4, “ReturnIfAbrupt Shorthands.” So “! ToInt32(x)” in the text says to execute “ToInt32(x)” according to certain rules, not to apply a logical negation to “ToInt32(x)”.

Related