From d05d698a0b2d9ffc1282d84f5b9fb67bbeb0e030 Mon Sep 17 00:00:00 2001 From: flywind Date: Sat, 19 Dec 2020 19:27:02 +0800 Subject: [PATCH 1/2] add --- changelog.md | 2 ++ lib/pure/math.nim | 20 ++++++++++++++++++++ tests/stdlib/tmath.nim | 21 +++++++++++++++++++++ 3 files changed, 43 insertions(+) diff --git a/changelog.md b/changelog.md index 01eff1cd73ea1..d811dbfa9c090 100644 --- a/changelog.md +++ b/changelog.md @@ -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`. diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 5f3261f1af512..66cc85653ff7b 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -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) diff --git a/tests/stdlib/tmath.nim b/tests/stdlib/tmath.nim index 18e42cbdcbc03..97c8c978a9442 100644 --- a/tests/stdlib/tmath.nim +++ b/tests/stdlib/tmath.nim @@ -293,3 +293,24 @@ template main = main() static: main() + +when not defined(js): + proc testGen() = + template impl(num) = + doAssert fromBits(toBits(float64(num))) == float64(num) + echo fromBits(toBits(float32(num))) + echo float32(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() From f8e8409647bd0a6b0bd4c313ff2293af7240c36c Mon Sep 17 00:00:00 2001 From: flywind Date: Sat, 19 Dec 2020 20:21:18 +0800 Subject: [PATCH 2/2] make --- tests/stdlib/tmath.nim | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/stdlib/tmath.nim b/tests/stdlib/tmath.nim index 97c8c978a9442..01c4c26e129b4 100644 --- a/tests/stdlib/tmath.nim +++ b/tests/stdlib/tmath.nim @@ -298,8 +298,6 @@ when not defined(js): proc testGen() = template impl(num) = doAssert fromBits(toBits(float64(num))) == float64(num) - echo fromBits(toBits(float32(num))) - echo float32(num) doAssert fromBits(toBits(float32(num))) == float32(num) impl(0)