Converting 'float' to 'byte[4]' and back to 'float' in .NET Micro Framework

chris12892 picture chris12892 · Jan 20, 2011 · Viewed 28.8k times · Source

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.

Answer

MarkPflug picture MarkPflug · May 12, 2011

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;
}