Converting Vector3 to Byte[]?

Hi, I’m looking for a efficient way to convert a Vector3 to a Byte array as I’m writing a program that’ll send this Byte over to the server.

Currently what i have in mind is this:

Vector3 vector = Vector3.Zero;
    
byte[] array = new byte[3];
    
array[0] = vector.x;
array[1] = vector.y;
array[2] = vector.z;

Are there any other elegant ways to do this instead?

Use BitConverter.GetBytes to convert each float (x,y,z) into bytes and put them into an array.

Something like this

byte[] bytes = new bytes[12]; // 4 bytes per float

Buffer.BlockCopy( BitConverter.GetBytes( ourVec.x ), 0, bytes, 0, 4 );
Buffer.BlockCopy( BitConverter.GetBytes( ourVec.y ), 0, bytes, 4, 4 );
Buffer.BlockCopy( BitConverter.GetBytes( ourVec.z ), 0, bytes, 8, 4 );

Use the BitConverter class, keeping in mind that it does not take processor endianness into account.

Pure elegance with generic functions <3 Works like a charm!

Edit: Well I should give an example how your final code should look like with the link given:

Vector3 vector = Vector3.Zero;
byte[] array = InfoSender.SerializeObject(vector);

I wrote an accoriding genereic deserialize function that wasn’t given in the link, very handy:

public static _T DeserializeObject<_T>(byte[] dataStream)
{
	MemoryStream memStr = new MemoryStream(dataStream);
	memStr.Position = 0;
	BinaryFormatter bf = new BinaryFormatter();
	bf.Binder = new VersionFixer();

	return (_T)bf.Deserialize(memStr);
}

Convert from Vector3 to byte :

byte[] buff = new byte[sizeof(float)*3]; 		
Buffer.BlockCopy( BitConverter.GetBytes( vect.x ), 0, buff, 0*sizeof(float), sizeof(float) );
Buffer.BlockCopy( BitConverter.GetBytes( vect.y ), 0, buff, 1*sizeof(float), sizeof(float) );
Buffer.BlockCopy( BitConverter.GetBytes( vect.z ), 0, buff, 2*sizeof(float), sizeof(float) );

Convert from byte to Vector3:

byte[] buff = data;
Vector3 vect = Vector3.zero;
vect.x = BitConverter.ToSingle(buff,0*sizeof(float));
vect.y = BitConverter.ToSingle(buff,1*sizeof(float));
vect.z = BitConverter.ToSingle(buff,2*sizeof(float));