What's the best way to convert a float
to a byte[4]
and then back to a 'float'?
I am doing this in C# .NET Micro Framework, so there is no BitConverter
available for my use.
The conversion from uint
to float
(and reverse) can be done with "safe" code as well (though I don't know if this is possible on the NETMF or not).
[StructLayout(LayoutKind.Explicit)]
struct UIntFloat
{
[FieldOffset(0)]
public float FloatValue;
[FieldOffset(0)]
public uint IntValue;
}
public static float ToSingle(byte[] value, int index)
{
uint i = ToUInt32(value, index);
return ToSingle(i);
}
public static float ToSingle(uint value)
{
UIntFloat uf = new UIntFloat();
uf.IntValue = value;
return uf.FloatValue;
}