-2

Possible Duplicate:
Convert an array of different value types to a byte array

I have 6 floats and I need to put them in an array of floats and then convert them to bytes. here we go:

float x= g.transform.position.x;
float y= g.transform.position.y;
float z= g.transform.position.z;
float alpha = g.transform.rotation.eulerAngles.x;
float theta = g.transform.rotation.eulerAngles.y;
float phi =  g.transform.rotation.eulerAngles.z;

What is the best way to convert an array of floats to a byte array?

3
  • 4
    stackoverflow.com/questions/1385829/… Commented Nov 28, 2012 at 8:40
  • Can you say a bit more about the goals of this? In particular which endianness you want? Commented Nov 28, 2012 at 8:50
  • @CodesInChaos, goal is put floats to an array, array of floats to byte's array and send this byte's array over UDP in big endianness, have you an idea how to do that? Commented Nov 28, 2012 at 9:16

5 Answers 5

2
byte[] data = new float[]{x,y,z,alpha,theta,phi}
                  .SelectMany(f => BitConverter.GetBytes(f)).ToArray();

or (depending on the consumer's computer architecture)

byte[] data = new float[]{x,y,z,alpha,theta,phi}
              .SelectMany(f => BitConverter.GetBytes(f).Reverse()).ToArray();

you may also want to use BitConverter.IsLittleEndian to decide which one to choose as @CodesInChaos suggested

Sign up to request clarification or add additional context in comments.

9 Comments

Note that this uses native endianness and is such unsuitable for persistent storage or network communication.
@CodesInChaos I already suggested serialization technique and gave an example to OP in his previous questions.
it would be great if there is something to do with a little to big endianness, the above solution shows up an error which says Type float[]' does not contain a definition for SelectMany' and no extension method SelectMany' of type float[]' could be found (are you missing a using directive or an assembly reference?)
@TimTaker a) include namespace System.Linq b) you can also try BitConverter.GetBytes(f).Reverse() but i don't think you will need this.
@L.B You should to check BitConverter.IsLittleEndian before reversing, even if .net/mono typically only run on little endian platforms.
|
0

If native endianness and LINQ is acceptable, L.B's answer is fine. If you want consistent (little) endianness, use a BinaryWriter:

using(var stream = new MemoryStream())
using(var writer = new BinaryWriter(stream))
{
   writer.Write(x);
   writer.Write(y);
   ...
   return stream.ToArray();
}

If you want to use big endianness you could use the following helper method:

byte[] GetBytesBigEndian(float f)
{
  var bytes = BitConverter.GetBytes(f);
  if(BitConverter.IsLittleEndian)
    Array.Reverse(bytes);
  return bytes;
}

using(var stream = new MemoryStream())
using(var writer = new BinaryWriter(stream))
{
   writer.Write(GetBytesBigEndian(x));
   writer.Write(GetBytesBigEndian(y));
   ...
   return stream.ToArray();
}

If that's too slow, there are also a few unsafe tricks to that can speed it up a bit.

2 Comments

is there a way to use this method without linq?
@TimTaker Added a version that doesn't depend on LINQ.
0
float[] source = new float[100];
byte[] dest = new byte[source.Length * sizeof(float)];
Buffer.BlockCopy(source, 0, dest, 0, dest.Length);

Comments

0

try something like:

var farray = new float[] {12.4f, 12.3f, 4.5f}; // or what ever values you want.
var bArray = new byte[farray.Length];
Buffer.BlockCopy(farray, 0, bArray, 0, bArray.Length);
        foreach (byte value in bArray)
            Console.Write("{0}  ", value);

for more information visit MSDN

Hope this helps.

1 Comment

is it possible to do this through array list?
0

Here's a cheeky way:

float x = 1F;
float y = 2F;
float z = 3F;
float alpha = 4F;
float theta = 5F;
float phi = 6F;
byte[] raw = new byte[6 * sizeof(float)];
fixed (byte* ptr = raw)
{
    float* typed = (float*)ptr;
    typed[0] = x;
    typed[1] = y;
    typed[2] = z;
    typed[3] = alpha;
    typed[4] = theta;
    typed[5] = phi;
}
return raw;

Note, however, that it makes assunptions about endianness. You might want to check BitConverter.IsLittleEndian and reverse each 4-byte chunk if necessary.

Of course, if you can re-use an existing buffer, that is preferable. Same approach - just pass in an existing byte[] as a parameter rather than creating a new one each time.

1 Comment

oh..sorry I can't use unsafe contest

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.