Skip to content

fixes #22326; JS: cast between floats and integers reinterprets the bits - #26883

Open
jasagiri wants to merge 1 commit into
nim-lang:develfrom
jasagiri:js-cast-bits
Open

jasagiri wants to merge 1 commit into
nim-lang:develfrom
jasagiri:js-cast-bits

Conversation

@jasagiri

@jasagiri jasagiri commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

fixes #22326

The manual says cast reinterprets the bits, and the C backend does so. jsgen's genCast did not for floats and integers: it either left the Number as it was or converted it numerically.

expression JS before C, and JS after
cast[uint32](1.5'f32) stays the Number 1.5 (printing it throws a RangeError) 1069547520 (0x3FC00000)
cast[int64](1.5) RangeError: 1.5 cannot be converted to a BigInt 4609434218613702656
cast[float](0x4059000000000000'i64) 4636737291354636000.0 100.0

genCast is where the JS backend decides what a cast means, so the fix is there: when one side is a float and the other a float or integer of another kind, the source is stored in a little-endian DataView and the destination is read back from it. 64-bit integers go through setBigInt64/getBigInt64 and are wrapped with BigInt(...)/Number(...) when they are Numbers (--jsbigint64:off). float and float64 stay a no-op.

This also fixes std/formatfloat.writeFloatToBufferRoundtrip on JS (reported in the issue), whose dragonbox and schubfach read the float's bits with cast: it printed 5e-324 for 1.5 and now prints 1.5. The local workaround in std/hashes (toBits on JS) is left as it is.

Test: tests/js/tcastfloatbits.nim runs the same assertions on C and JS, each with --jsbigint64:on and off (the formatfloat part only where 64-bit integers are exact). Checked on macOS arm64 with node 26: the new test 4/4, testament cat js 260 passed and 0 failed, tests/stdlib/thashes.nim and tests/float/tfloats.nim pass on all their targets.

🤖 Generated with Claude Code

…rets the bits

The spec says `cast` reinterprets the bits, and the C backend does so,
but jsgen converted the value numerically: `cast[uint32](1.5'f32)`
gave 1 and `cast[int64](1.5)` threw (BigInt of a non-integer). Casts
where one side is a float and the other a float or integer of another
kind now store the source in a little-endian DataView and read the
destination back from it. This also fixes
`std/formatfloat.writeFloatToBufferRoundtrip` on JS, whose dragonbox
and schubfach read the float's bits with `cast`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

casting between ints and float has different behaviour on JS backend

1 participant