How to convert from ubyte[] to and from float?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Oct 18 21:59:15 PDT 2014
On 10/18/2014 06:06 PM, Charles Hixson via Digitalmars-d-learn wrote:
> What is the best way to convert from a part of a ubyte[] to a float?
>
> I've tried converting the ubyte[] into a uint, but neither casting the
> uint to a float nor to!float work.
>
> I suppose I could use a "trick record" union, but that seems inelegant.
> If I use pointers, the alignment may (unpredictably) not be proper
> (whatever that means these days).
This is what I understood:
import std.exception;
ubyte[float.sizeof] toBytes(float f)
{
ubyte* beg = cast(ubyte*)&f;
return beg[0..f.sizeof];
}
float toFloat(const(ubyte)[] bytes)
{
enforce(bytes.length >= float.sizeof);
return *cast(float*)bytes.ptr;
}
void main()
{
float f = 1.5;
auto bytes = toBytes(f);
float f2 = toFloat(bytes);
assert(f2 == f);
}
There are no alignment issues because f and ubyte[float.sizeof] are not
related. If you meant that ubyte[] should be a reference to an existing
float, then toBytes must take by 'ref float' and then it can return a
ubyte[]. However, it would be the responsibility of the caller to ensure
that the float would live long enough.
If that happened, then there would be no alignment issues because we
would have started with a float anyway and the ubyte[] would be
referring to that float in memory.
Ali
More information about the Digitalmars-d-learn
mailing list