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