GLBasic forum

Main forum => GLBasic - en => Topic started by: Marmor on 2015-Oct-27

Title: how to convert 4 bytes to
Post by: Marmor on 2015-Oct-27
a float ?  can anyone help?
Title: Re: how to convert 4 bytes to
Post by: MrTAToad on 2015-Oct-28
Do the original 4 bytes make up a float ?  Or is it something else ?
Title: Re: how to convert 4 bytes to
Post by: Marmor on 2015-Oct-28
Yap its a original 32 bit float .
Title: Re: how to convert 4 bytes to
Post by: MrTAToad on 2015-Oct-28
You should be able to use READSHORTIEEE in that case
Title: Re: how to convert 4 bytes to
Post by: Schranz0r on 2015-Oct-28
+1

MrTAToad
Title: Re: how to convert 4 bytes to
Post by: Slydog on 2015-Oct-28
If you're not reading this from a file, can you use an INLINE C++ Union? (Map the four bytes to a float).
I haven't programmed in C++ in 10+ years, no idea if this is an option, or even what you're looking for.
Title: Re: how to convert 4 bytes to
Post by: Marmor on 2015-Oct-28
yap union and inline c are the right way.


thx
Title: Re: how to convert 4 bytes to
Post by: bigsofty on 2015-Oct-28
Not my code but here it is in C, two forms, one for each endianess.

Code (glbasic) Select
float bytesToFloatA(uchar b0, uchar b1, uchar b2, uchar b3)
{
    float output;

    *((uchar*)(&output) + 3) = b0;
    *((uchar*)(&output) + 2) = b1;
    *((uchar*)(&output) + 1) = b2;
    *((uchar*)(&output) + 0) = b3;

    return output;
}


float bytesToFloatB(uchar b0, uchar b1, uchar b2, uchar b3)
{
    float output;

    *((uchar*)(&output) + 3) = b3;
    *((uchar*)(&output) + 2) = b2;
    *((uchar*)(&output) + 1) = b1;
    *((uchar*)(&output) + 0) = b0;

    return output;
}

float (*correctFunction)(uchar b0, uchar b1, uchar b2, uchar b3) = bytesToFloatA;

if ((*correctFunction)(0x3e, 0xaa, 0xaa, 0xab) != 1.f/3.f) // horrifying, I know
{
  correctFunction = bytesToFloatB;
}


Should be quite easy to inline.
Title: Re: how to convert 4 bytes to
Post by: MrTAToad on 2015-Oct-29
You just have to make sure the order is correct, otherwise might get the wrong value.  You could also use memcpy if you know if the endianess doesn't change.