none
Float array into a byte array

    Question

  • Using BitConverter. GetBytes (), the length of 50 float array, to a length of 200 byte array, how to do?

    please verify my account

    Thursday, April 20, 2017 3:41 AM

Answers

  • 1) Declare a variable of type List<byte>.
    2) Write for-loop to loop the float array, call BitConverter.GetBytes() for each item and pass the result to .AddRange() of the variable in step 1.
    3) Return .ToArray() of the variable in step 1.

    • Marked as answer by lctk Friday, April 21, 2017 3:45 AM
    Thursday, April 20, 2017 5:33 AM
    Answerer
  • Try this too:

    float[] floats = new float[50];
    // . . .
    byte[] bytes = new byte[sizeof( float ) * floats.Length];
    
    var p = GCHandle.Alloc( bytes, GCHandleType.Pinned );
    Marshal.Copy( floats, 0, p.AddrOfPinnedObject(), floats.Length );
    p.Free();

    However it does not use BitConverter.
    • Edited by Viorel_MVP Thursday, April 20, 2017 5:53 AM
    • Marked as answer by lctk Friday, April 21, 2017 3:45 AM
    Thursday, April 20, 2017 5:52 AM
  • Buffer.BlockCopy is able to copy from float[] to byte[] and does not need a GCHandle.
    • Marked as answer by lctk Friday, April 21, 2017 3:45 AM
    Thursday, April 20, 2017 9:52 AM

All replies

  • 1) Declare a variable of type List<byte>.
    2) Write for-loop to loop the float array, call BitConverter.GetBytes() for each item and pass the result to .AddRange() of the variable in step 1.
    3) Return .ToArray() of the variable in step 1.

    • Marked as answer by lctk Friday, April 21, 2017 3:45 AM
    Thursday, April 20, 2017 5:33 AM
    Answerer
  • Try this too:

    float[] floats = new float[50];
    // . . .
    byte[] bytes = new byte[sizeof( float ) * floats.Length];
    
    var p = GCHandle.Alloc( bytes, GCHandleType.Pinned );
    Marshal.Copy( floats, 0, p.AddrOfPinnedObject(), floats.Length );
    p.Free();

    However it does not use BitConverter.
    • Edited by Viorel_MVP Thursday, April 20, 2017 5:53 AM
    • Marked as answer by lctk Friday, April 21, 2017 3:45 AM
    Thursday, April 20, 2017 5:52 AM
  • Buffer.BlockCopy is able to copy from float[] to byte[] and does not need a GCHandle.
    • Marked as answer by lctk Friday, April 21, 2017 3:45 AM
    Thursday, April 20, 2017 9:52 AM