float to byte[4] to float without using BitConverter?

本文关键字:float to using without BitConverter byte | 更新日期: 2023-09-27 18:36:09

如何在不使用BitConverter的情况下将浮点数转换为字节数组,然后将字节数组重新转换为浮点数?

提前谢谢。

float to byte[4] to float without using BitConverter?

如果byte[]的字节序与float的字节序相同:

[StructLayout(LayoutKind.Explicit)]
public struct UInt32ToSingle
{
    [FieldOffset(0)]
    public uint UInt32;
    [FieldOffset(0)]
    public float Single;
    [FieldOffset(0)]
    public byte Byte0;
    [FieldOffset(1)]
    public byte Byte1;
    [FieldOffset(2)]
    public byte Byte2;
    [FieldOffset(3)]
    public byte Byte3;
}
public static float FromByteArray(byte[] arr, int ix = 0)
{
    var uitos = new UInt32ToSingle
    {
        Byte0 = arr[ix],
        Byte1 = arr[ix + 1],
        Byte2 = arr[ix + 2],
        Byte3 = arr[ix + 3],
    };
    return uitos.Single;
}
public static byte[] ToByteArray(float f)
{
    byte[] arr = new byte[4];
    ToByteArray(f, arr, 0);
    return arr;
}
public static void ToByteArray(float f, byte[] arr, int ix = 0)
{
    var uitos = new UInt32ToSingle { Single = f };
    arr[ix] = uitos.Byte0;
    arr[ix + 1] = uitos.Byte1;
    arr[ix + 2] = uitos.Byte2;
    arr[ix + 3] = uitos.Byte3;
}

请注意,我在UInt32ToSingle结构上做了一些作弊,就像一个C联合。我用它来从各种byte转换为float(由于FieldOffsetstruct的字段在内存中占据相同的位置)。

使用示例:

byte[] b = ToByteArray(1.234f);
float f = FromByteArray(b); // 1.234f