-4

How can I convert a float to an array of bytes then re-convert the byte array to float without using BitConverter??

Thanks in advance.

1 Answers1

3

If the endianness of the byte[] is the same as the endianness of the 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;
}

Note that I'm doing a little cheating with the UInt32ToSingle struct, that is like a C union. I use it to convert from the various byte to float (the fields of the struct occupy the same place in memory, thanks to the FieldOffset).

Example of use:

byte[] b = ToByteArray(1.234f);
float f = FromByteArray(b); // 1.234f
xanatos
  • 109,618
  • 12
  • 197
  • 280
  • what about getting the bytes without using BitConverter?? – Mohamed Mokhtar Feb 25 '16 at 17:02
  • @MohamedMokhtar By cheating a little more it is easy. – xanatos Feb 25 '16 at 17:09
  • I think you can use unsafe code. If `f` is your `float` value, take `&f` which is the "address of" it and has pointer type `float*`. You can just cast that pointer to `byte*` which works more or less like an array already. You can take a pointer to an actual `new byte[]` of course, and copy to that, similar to [How to: Use Pointers to Copy an Array of Bytes (C# Programming Guide)](https://msdn.microsoft.com/en-us/library/28k1s2k6.aspx). – Jeppe Stig Nielsen Jan 28 '17 at 21:29
  • @JeppeStigNielsen Yep, you can surely use unsafe code. And it is exactly how the `BitConverter` does it undercover – xanatos Feb 02 '17 at 13:40
  • this is awesome – chantey Jun 23 '19 at 03:25