2

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.

2
  • The bitwise operators internally convert the normal "number" values to 32-bit integers, do their work, and then create new double-precision values as their results. Commented Jul 8, 2021 at 2:50
  • 2
    Note also that all 32-bit integers can be represented exactly as 64-bit floats. I am also an old geezer. Commented Jul 8, 2021 at 2:50

1 Answer 1

1

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)”.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.