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

后端 未结 3 1684
清歌不尽
清歌不尽 2020-12-06 13:17

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

3条回答
  •  时光取名叫无心
    2020-12-06 14:09

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

提交回复
热议问题