Re:The secret life of NaN
by stcredzero on Thursday April 05, 2018 @03:52PM
(#16768310)
Could this be used to hide data in Javascript programs?
As per TFA, some implementations use NaN-boxing to represent other values (all values are encoded into NaN). In those implementations, you will have pretty strange behaviour. V8 doesn't use NaN-boxing so it will work there.
Of course NaN-boxing is the reason that the ECMA spec specifies that all NaNs are treated equally. If you are encoding all of your values in NaN, you still have to have one NaN value that is actually NaN. The spec doesn't specify which one that must be.
BTW, I highly recommend reading TFA and the links within, because it's really fascinating (the "tagged-pointers" used in V8 and other languages like Guile are also really interesting).
You'd be relying on undefined behavior by the ECMAScript spec, but sure. Whether it works is implementation dependent, and you'd have no grounds for complaint if it changed at any time.
Playing around with it in Chrome 65.0.*...
const buffer = new ArrayBuffer(12);
const uint8s = new Uint8Array(buffer);
const floats = new Float32Array(buffer);
floats[0] = NaN, floats[1] = NaN; //127.192.0.0, 127.192.0.0, 0.0.0.0
uint8s[0] = 104, uint8s[1] = 105; //127.192.104.105, 127.192.0.0, 0.0.0.0
floats[2] = floats[0] + floats[1]; //127.192.104.105, 127.192.0.0, 127.192.104.105
console.log(String.fromCharCode(uint8s[8]) + String.fromCharCode(uint8s[9]));
> 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. (Note that the NaN value is produced by the program expression NaN.) 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.
> The bit pattern that might be observed in an ArrayBuffer (see 24.1) or a SharedArrayBuffer (see 24.2) after a Number value has been stored into it is not necessarily the same as the internal representation of that Number value used by the ECMAScript implementation.
[0] https://www.ecma-international.org/ecma-262/8.0/index.html#s...