How to get the IEEE 754 binary representation of a float in C#

后端 未结 2 1220
小鲜肉
小鲜肉 2020-12-09 09:15

I have some single and double precision floats that I want to write to and read from a byte[]. Is there anything in .Net I can use to convert them to and from their 32 and 6

相关标签:
2条回答
  • 2020-12-09 09:56

    .NET Single and Double are already in IEEE-754 format. You can use BitConverter.ToSingle() and ToDouble() to convert byte[] to floating point, GetBytes() to go the other way around.

    0 讨论(0)
  • 2020-12-09 10:02

    Update for current .NET/C# using spans:

    static void Main()
    {
        Span<byte> data = stackalloc byte[20];
        GetBytes(0, data, 0);
        GetBytes(123.45F, data, 4);
        GetBytes(123.45D, data, 8);
    }
    
    static unsafe void GetBytes(float value, Span<byte> buffer, int offset)
        => MemoryMarshal.Cast<byte, float>(buffer.Slice(offset))[0] = value;
    static unsafe void GetBytes(double value, Span<byte> buffer, int offset)
        => MemoryMarshal.Cast<byte, double>(buffer.Slice(offset))[0] = value;
    

    If you don't want to allocate new arrays all the time (which is what GetBytes does), you can use unsafe code to write to a buffer directly:

    static void Main()
    {
        byte[] data = new byte[20];
        GetBytes(0, data, 0);
        GetBytes(123.45F, data, 4);
        GetBytes(123.45D, data, 8);
    }
    
    static unsafe void GetBytes(float value, byte[] buffer, int offset)
    {
        fixed (byte* ptr = &buffer[offset])
        {
            float* typed = (float*)ptr;
            *typed = value;
        }
    }
    static unsafe void GetBytes(double value, byte[] buffer, int offset)
    {
        fixed (byte* ptr = &buffer[offset])
        {
            double* typed = (double*)ptr;
            *typed = value;
        }
    }
    
    0 讨论(0)
提交回复
热议问题