勉強会@Online 31 Zfa: 思わぬ動的言語への影響 (2) JavaScript において、Number の表現を FP64 → Int32 に変換する操作は結構複雑。 (ECMAScript 抽象操作: ToInt32 / ToUint32) V8 ソースコードより引用: src/numbers/conversions-inl.h // Implements most of https://tc39.github.io/ecma262/#sec-toint32. int32_t DoubleToInt32(double x) { if ((std::isfinite(x)) && (x <= INT_MAX) && (x >= INT_MIN)) { // All doubles within these limits are trivially convertable to an int. return static_cast<int32_t>(x); } base::Double d(x); int exponent = d.Exponent(); uint64_t bits; if (exponent < 0) { if (exponent <= -base::Double::kSignificandSize) return 0; bits = d.Significand() >> -exponent; } else { if (exponent > 31) return 0; // Masking to a 32-bit value ensures that the result of the // static_cast<int64_t> below is not the minimal int64_t value, // which would overflow on multiplication with d.Sign(). bits = (d.Significand() << exponent) & 0xFFFFFFFFul; } return static_cast<int32_t>(d.Sign() * static_cast<int64_t>(bits)); }