Skip to content
Advertisement

Are JS engines allowed to change the bits of a NaN?

In JavaScript, the NaN value can be represented by a wide range of 64-bit doubles internally. Specifically, any double with the following bitwise representation:

x111 1111 1111 xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx xxxx

Is interpreted as a NaN. My question is: suppose I cast two 32-bit uints to a JS Number using ArrayBuffers, pass it around, then cast it back to two 32-bit uints. Will the recovered bits be the same as the original, or are JS engines allowed to change the bits of a NaN at will? In other words, can JS numbers be used to store 64-bits losslesly?

Advertisement

Answer

ECMA-262 9th Edition, June 2018, (the standard to which JavaScript is intended to conform) says, in 6.1.6 “The Number Type”:

… the 9007199254740990 (that is, 253-2) distinct “Not-a-Number” values of the IEEE Standard are represented in ECMAScript as a single special NaN value.… In some implementations, external code might be able to detect a difference between various Not-a-Number values, but such behaviour is implementation-dependent; to ECMAScript code, all NaN values are indistinguishable from each other.

24.1.17 “NumberToRawBytes ( type, value, isLittleEndian )” says:

… If value is NaN, rawBytes may be set to any implementation chosen IEEE 754-2008 binary64 format Not-a-Number encoding. An implementation must always choose the same encoding for each implementation distinguishable NaN value.…

I do not see any other passages that mention NaN that are illuminating on this question. On one hand, 24.1.17 effectively tells us the bits of a NaN must be preserved when converting the NaN to raw bytes. However, nothing else appears to tell us the bits must be preserved in other operations. One might deduce that this is the intent, because this requirement in 24.1.17 would serve no purpose if the bits could be arbitrarily changed by any other operation. But I would not rely on JavaScript implementations to have implemented this in conformance with that intent.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement