How to serialize a double.
Jake Pittis via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Dec 1 11:09:02 PST 2016
On Thursday, 1 December 2016 at 07:13:45 UTC, Bauss wrote:
> On Thursday, 1 December 2016 at 00:36:30 UTC, Jake Pittis wrote:
>> [...]
>
> You could do something like below which will allow you to
> serialize any number.
>
> ````
> import std.stdio : writeln;
> import std.traits : isNumeric;
>
> ubyte[] bytes(T)(T num) if (isNumeric!T) {
> auto buf = new ubyte[T.sizeof];
>
> (*cast(T*)(buf.ptr)) = num;
>
> return buf;
> }
>
> T value(T)(ubyte[] buf) if (isNumeric!T) {
> return (*cast(T*)(buf.ptr));
> }
> ````
>
> And example usage:
> ````
> double foo = 3.14;
>
> writeln(foo); // Prints 3.14
>
> ubyte[] bar = foo.bytes;
>
> writeln(bar); // Prints the bytes equal to 3.14
>
> foo = bar.value!double;
>
> writeln(foo); // Prints 3.14
> ````
Regarding the test assertion that failed. Turns out I had a bug
in the test. (of course)
This last solution is very pretty. Thanks.
You folks are all so kind!
More information about the Digitalmars-d-learn
mailing list