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

最后都变了- 提交于 2019-11-28 08:19:08

.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.

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!