How to serialize a double.

Bauss via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Nov 30 23:13:45 PST 2016


On Thursday, 1 December 2016 at 00:36:30 UTC, Jake Pittis wrote:
> How do I convert a double to a ubyte[]?
>
> I've tried all sorts of things including converting the double 
> to a ulong and trying to serialize the ulong. For example test 
> bellow fails.
>
> ````
> unittest {
>     double d = 3.14;
>     ulong l = *cast(ulong*)(&d);
>     double after = *cast(double*)(&l));
>     assert(after == d); // This fails.
> }
> ````

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
````


More information about the Digitalmars-d-learn mailing list