Unsigned long to double and back

Johannes Kuhn info at j-kuhn.de
Sun Nov 6 00:17:19 UTC 2022


When I tried to implement an WASM transpiler, I noticed some missing 
conversion methods from unsigned types to floating point, for example 
from unsigned long to a double.

For the meaning of unsigned long, see Long.toUnsignedString(long i).

Converting between unsigned long and floating point is not a trivial 
task, as it probably requires some bit manipulation.

In particular, I would love to see the following methods added*:

- double Double.fromUnsignedLong(long i)
- long Double.toUnsignedLong(double d)
- float Float.fromUnsignedLong(long i)
- long Float.toUnsignedLong(float f)

* Subject to bikeshedding - I don't care about the name, or if it is 
added to the Long class.

Currently, I don't think that additional methods for unsigned int are 
necessary - as it is possible to cast between long and int, but feel 
free to correct me.

In WASM, the specification for those methods can be found here:

https://www.w3.org/TR/wasm-core-1/#op-trunc-u
https://www.w3.org/TR/wasm-core-1/#op-convert-u

Note that the WASM specification is undefined for some values, notably 
NaN, infinities, and values that fall out of the range.

As *I* want to use it to implement WASM instructions, I do not have any 
strong opinion on the undefined cases - for example, returning the 
nearest unsigned long value or throwing an exception is fine for me.

What do you think?

- Johannes


More information about the core-libs-dev mailing list