How do I convert an array of floats to a byte[] and back?

后端 未结 4 705
臣服心动
臣服心动 2020-12-02 15:38

I have an array of Floats that need to be converted to a byte array and back to a float[]... can anyone help me do this correctly?

I\'m working with the bitConvert

4条回答
  •  忘掉有多难
    2020-12-02 15:55

    If you're looking for performance then you could use Buffer.BlockCopy. Nice and simple, and probably about as fast as you'll get in managed code.

    var floatArray1 = new float[] { 123.45f, 123f, 45f, 1.2f, 34.5f };
    
    // create a byte array and copy the floats into it...
    var byteArray = new byte[floatArray1.Length * 4];
    Buffer.BlockCopy(floatArray1, 0, byteArray, 0, byteArray.Length);
    
    // create a second float array and copy the bytes into it...
    var floatArray2 = new float[byteArray.Length / 4];
    Buffer.BlockCopy(byteArray, 0, floatArray2, 0, byteArray.Length);
    
    // do we have the same sequence of floats that we started with?
    Console.WriteLine(floatArray1.SequenceEqual(floatArray2));    // True
    

提交回复
热议问题