Re: FLOAT to INT and back again.
Posted: Sat Feb 08, 2020 10:42 pm
You could try to use float for the union member in stead of the MX_FLOAT. That should result in a 4 byte float.
Old forums - please visit https://www.flowcode.co.uk/forums
https://www.flowcode.co.uk/mmforums/
No Martin.mnf wrote:So - you want to convert the value to a 32bit integer (rather than a 32bit float)?
What range of values are you working with and how many points of accuracy do you need?
Taking the byte 'values' of the fp number isn't the way to go here (it would be possible - but difficult)
Could you - for example - use(and let the compiler take the strain)Code: Select all
.UL = .x * 1000
Which converts (in my example above) .x (a float) to 1234 (.UL an unsigned long)
There was an interesting piece in stackoverflow about how the number of bits in the exponent and mantissa was decided upon - can't just find the link at the moment.
The Flowcode wiki describes floats as representing numbers from -infinity to +infinity - and while this is true - it might need a few more bits to hold all the numbers accurately?![]()
Martin
I'm not sure what you mean by this. Could you give more info please?kersing wrote:You could try to use float for the union member in stead of the MX_FLOAT. That should result in a 4 byte float.
Code: Select all
.f32 = .f64
Code: Select all
FCL_F32 = (float) FCL_F64;
Code: Select all
typedef union
{
float AsFloat;
MX_UINT8 AsByte[4];
} MX_FloatUnion;
MX_FloatUnion FloatUnion;
Hi, Thanks for this. It works perfectly now.kersing wrote:Change your union to:
Assign the value to AsFloat and get the bytes from the 4 AsByte vast like your earlier example.Code: Select all
typedef union { float AsFloat; MX_UINT8 AsByte[4]; } MX_FloatUnion; MX_FloatUnion FloatUnion;
Code: Select all
FloatUnion.AsByte[0] = FCV_TEMP_UNION_STR[0];
FloatUnion.AsByte[1] = FCV_TEMP_UNION_STR[1];
FloatUnion.AsByte[2] = FCV_TEMP_UNION_STR[2];
FloatUnion.AsByte[3] = FCV_TEMP_UNION_STR[3];
FCV_TEMP_UNION_FLOAT = FloatUnion.AsFloat;