Convert from byte array to float...

I have a 32 bit float represented by four bytes and I need to convert it to a float type, how

 

Thanks,

 

Devin



Answer this question

Convert from byte array to float...

  • SlowBowler

    It's actually a lot simpler to just use the BitConverter class which is available on all 3 platforms (1.0 - 2.0).

    float floatValue = BitConverter.ToSingle(<yourByteArrayGoesHere>);

    Do a search on BitConverter.ToSingle if you would like specific information from MSDN.

     

    Ben


  • PugRallye

    You could also use a 'Union' to pull this off:


    using System.Runtime.InteropServices;

    [StructLayout(LayoutKind.Explicit)]
    public struct Union {
        [FieldOffset(0)] public float FloatValue;

        [FieldOffset(0)] public byte ByteValue0;
        [FieldOffset(1)] public byte ByteValue1;
        [FieldOffset(2)] public byte ByteValue2;
        [FieldOffset(3)] public byte ByteValue3;
    }

     


    In the above struct the 4 bytes and the float occupy the same space in memory; setting one will set the other.



  • DarrenONeill111

    thanks guys, that's neat to see thos examples as I will use at least two of them in the near future.
  • ghamm

    Probably the quickest way is to use a MemoryStream and a BinaryReader/Writer combo, e.g:

            Dim ms As New MemoryStream
            Dim bw As New BinaryWriter(ms)
            Dim br As New BinaryReader(ms)
            Dim FloatBytes() As Byte
            Dim MyFloat As Single = 3.1415927
            bw.Write(MyFloat)
            ms.Seek(0, SeekOrigin.Begin)
            FloatBytes = br.ReadBytes(4)
            br.Close()
            bw.Close()
            ms.Close()

    (This performs the conversion in the opposite direction of what you want, but the idea should be clear...). The only gotcha is that the byte ordering of your float may be opposite of how the BinaryReader/Writer handles it (mantissa first instead of sign/exponent first). But even if you have to use 4 individual BinaryReader.Writes to write the bytes in the right order, performance should still be OK.

    '//mdb



  • Convert from byte array to float...