- Home /
How change float to byte[] and then byte[] to float without accuracy lost?
I use google play game services for unity. Send packet look like this:
byte[] mPosPacket = new byte[4];
public void BroadCastPosition() {
mPosPacket[0] = (byte) 'P';
mPosPacket [1] = (byte)position.x;
mPosPacket [2] = (byte)position.y;
mPosPacket [3] = (byte)position.z;
PlayGamesPlatform.Instance.RealTime.SendMessageToAll(false, mPosPacket);
}
Recive look like this:
public void OnRealTimeMessageReceived(bool isReliable, string senderId, byte[] data) {
if (data [0] == (byte)'P') {
posX = (float)data [1];
posY = (float)data [2];
posZ = (float)data [3];
}
With this everything work but for example when send float 2.4243, recive float 2. I need more accurate. When I use System.bitconverter float is super accurate but i can't give something like this "mPosPacket[0] = (byte) 'P';" Anyone know way to recognize byte or use bitconverter to start with 1 index?
I need something like this:
mPosPacket[0] = (byte) 'P';
mPosPacket[1], mPosPacket[2], mPosPacket[3] is one float
Answer by Jeff-Kesselman · May 04, 2014 at 03:02 PM
Use DataStream to convert primitive types to their byte repesentations and back
http://msdn.microsoft.com/en-us/library/aa271346(v=vs.60).aspx
Edit: Actually in c# you use BinaryWriter, my mistake. Its the same basic thing though
float f = 3.1415;
MemoryStream stream = new MemoryStream();
BinaryWriter bw = new BinaryWriter(stream);
bw.Write(f);
bw.Flush();
byte[] floatBytes = stream.ToArray();
Do the reverse with BinaryReader to convert back.
Note that, rather then doing this for each float, you can create one stream that has all your data in it with successive writes and get it back with successive reads.
How can you use $$anonymous$$emoryStream and BinaryWriter in Unity? I don't have this class.
You just need to make sure you are importing System.IO
in C# you do this as the top of the file with:
using System.IO;
How can I read specific float, when I (send, then) recive only byte[]?
Your answer
Follow this Question
Related Questions
Converting a float to a byte[]? Not working 2 Answers
Conversion of float[] to byte[] is too slow, how to optimize this? 0 Answers
Multiplayer Rigidbody Vibration 2 Answers
convert object to float 2 Answers
How to convert 00:40:00.0 to float 2 Answers