How to convert byte array to float

byron via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jul 17 12:11:31 PDT 2015


On Friday, 17 July 2015 at 19:03:46 UTC, Jacob Carlborg wrote:
> On 2015-07-17 20:58, byron wrote:
>
>> Ah I miss read, if you want as a float, not a float array you 
>> can do:
>>
>> byte[] b = [1, 2, 3, 4];
>> float f = *cast(float*)b.ptr;
>>
>> not sure if there is a better way
>
> I think a union can be used as well, not sure if it's better 
> though.

not a bad idea.

testing on asm.dlang.org both reduce to the same assembly
(-release -inline -O)

float pointerTest(inout byte[4] b) {
    return *cast(float*)b.ptr;
}

float unionTest(inout byte[4] b) {
   union U {
    byte[4] b;
     float f;
   }
   return U(b).f;
}


More information about the Digitalmars-d-learn mailing list