How to construct floats from bit-patterns in .NET?
In need to construct System.Single va开发者_StackOverflowlues (= IEEE 754 "single precision" 32-bit floats) from their bit pattern, represented as 4 bytes (or an int32 value, big endian).
How do I do this in .NET/F#?
You can turn a byte array into a Single using the BitConverter class
byte[] data = new byte[4];
float f = BitConverter.ToSingle(data, 0);
to go from an into to a byte array:
int i = 1234;
byte[] data = BitConverter.GetBytes(i);
(my code is in C#, but I'm sure it is easy enough for you to convert to F#)
You can use Buffer.BlockCopy
:
Assert.AreEqual(sizeof(float), sizeof(int));
int[] ints = ...
float[] result = new float[ints.Length];
Buffer.BlockCopy(ints, 0, result, 0, result.Length * sizeof(float));
The result
array will contain the floats that are represented by the bit patterns inside the ints
array. Each element in the ints
array represents the bit pattern of one float.
精彩评论