Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add toBits and fromBits to math #16403

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@
- `echo` and `debugEcho` will now raise `IOError` if writing to stdout fails. Previous behavior
silently ignored errors. See #16366. Use `-d:nimLegacyEchoNoRaise` for previous behavior.

- Added `toBits` and `fromBits` to math.

## Language changes

- `nimscript` now handles `except Exception as e`.
Expand Down
20 changes: 20 additions & 0 deletions lib/pure/math.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1131,3 +1131,23 @@ func lcm*[T](x: openArray[T]): T {.since: (1, 1).} =
while i < x.len:
result = lcm(result, x[i])
inc(i)


when not defined(js) and not defined(nimscript):
func toBits*(x: float64): uint64 {.since: (1, 5, 1).} =
## Returns the IEEE 754 binary representation of float64.
cast[uint64](x)

func toBits*(x: float32): uint32 {.since: (1, 5, 1).} =
## Returns the IEEE 754 binary representation of float32.
cast[uint32](x)

func fromBits*(x: uint64): float64 {.since: (1, 5, 1).} =
## Returns the floating-point number corresponding
## to the IEEE 754 binary representation.
cast[float64](x)

func fromBits*(x: uint32): float32 {.since: (1, 5, 1).} =
## Returns the floating-point number corresponding
## to the IEEE 754 binary representation.
cast[float32](x)
19 changes: 19 additions & 0 deletions tests/stdlib/tmath.nim
Original file line number Diff line number Diff line change
Expand Up @@ -293,3 +293,22 @@ template main =

main()
static: main()

when not defined(js):
proc testGen() =
template impl(num) =
doAssert fromBits(toBits(float64(num))) == float64(num)
doAssert fromBits(toBits(float32(num))) == float32(num)

impl(0)
impl(1)
impl(1000)
impl(-100)
impl(0.0)
impl(-0.0)
impl(3.1415926'f32)
impl(-3.1415926'f32)
impl(Inf)
impl(-Inf)

testGen()