- Home /
Converting a float to a byte[]? Not working
Okay, so all I simply need is to convert float (e.g 3.422
) and turn it into a byte[]
.
I need this because I am sending the byte as data for real time multiplayer. Everywhere I look online just have really complicated and different answers. I just need a simple way to convert my float into a byte array.
At present, I am using this:
float f = transform.position.y;
MemoryStream stream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(stream);
bw.Write(f);
bw.Flush();
byte[] floatBytes = stream.ToArray();
bool reliable = true;
PlayGamesPlatform.Instance.RealTime.SendMessageToAll (reliable, floatBytes);
But i dont know how to read this later on. So far I have:
MemoryStream stream = new MemoryStream ();
BinaryReader reader = new BinaryReader (stream);
But I don't know what do do from there.
Any help is greatly appreciated, thanks.
If you only want to convert bytes to floats and back then use the BitConverter class. It has a BitConverter.GetBytes(float) method that returns the bytes.
Answer by Munchy2007 · Dec 26, 2015 at 08:28 PM
Use float value = reader.ReadSingle();
But how do I specify which byte array to read? Say I have byte[] myByteArray
, how do i read the float from that?
Do I do $$anonymous$$emoryStream stream = new $$anonymous$$emoryStream(myByteArray)
?
Thanks
Answer by Measurity · Dec 27, 2015 at 01:00 AM
Use C#'s BitConverter class:
BitConverter.GetBytes(3.422)