I wrote this code for a multiplayer game I am developing to transmit floats over the network. It works, on the systems that I have tested it with. What I am worried about is the little-endian big-endian thing and the possibility of different float representations in general over computers. So here it goes:
private static ByteFloat bytefloat = new ByteFloat();
[StructLayout(LayoutKind.Explicit)] struct ByteFloat
{
[FieldOffset(0)] public float v;
[FieldOffset(0)] public byte a;
[FieldOffset(1)] public byte b;
[FieldOffset(2)] public byte c;
[FieldOffset(3)] public byte d;
}
public void setFloat(float v)
{
bytefloat.v = v;
setByte(bytefloat.a);
setByte(bytefloat.b);
setByte(bytefloat.c);
setByte(bytefloat.d);
}
public float getFloat()
{
bytefloat.a = getByte();
bytefloat.b = getByte();
bytefloat.c = getByte();
bytefloat.d = getByte();
return bytefloat.v;
}
I don't really want advice on variable naming or coding conventions, I just want to know if there are possible flaws with this code when the methods are called on different systems. I want to know if calling setFloat on some float, and sending the resulting bytes to any other computer, then calling getFloat on those bytes will result in the exact same value that I started with.
getByte() and setByte() do exactly what they say they do, this method pertains to a class which is a byte array wrapper, used for reading and writing data. (The backing byte array is sent over the network, and on the receiving side it is wrapped again and read from.)
If this code does not work across all systems, I would like a recommendation (or a solution) on how to write it in a way that is cross-system.
If this changes anything, I am working with the Unity platform and it's networking LLAPI (Raknet).