Is it possible to convert floats from big to little endian? I have a value from a big endian platform that I am sending via UDP to a Windows process (little endian). This value is a float, but when I am trying BitConverter.ToSingle I always get 5.832204E-42, but it should be 36.000.
What am I doing wrong?
Here is a code snipped:
// Receive thread
private void ReceiveData()
{
int count = 0;
IPEndPoint remoteIP = new IPEndPoint(IPAddress.Parse("10.0.2.213"), port);
client = new UdpClient(remoteIP);
while (true)
{
try
{
IPEndPoint anyIP = new IPEndPoint(IPAddress.Any, 0);
byte[] data = client.Receive(ref anyIP);
float x = BitConverter.ToSingle(data, 0);
float y = BitConverter.ToSingle(data, 4);
float z = BitConverter.ToSingle(data, 8);
float alpha = BitConverter.ToSingle (data, 12);
float theta = BitConverter.ToSingle (data, 16);
float phi = BitConverter.ToSingle (data, 20);
print(">> " + x.ToString() + ", "+ y.ToString() + ", "+ z.ToString() + ", " +
alpha.ToString() + ", "+ theta.ToString() + ", "+ phi.ToString());
// Latest UDP packet
lastReceivedUDPPacket=x.ToString()+" Packet#: "+count.ToString();
count = count+1;
}
36.0 and 5.832204E-42 are endian-opposites, so this is an endianness problem. On Windows / .NET, you are usually little-endian, so I'm guessing the data is big-endian. That means you need to reverse the data for each value, separately (not the entire array).
To write this in a way that is CPU-safe, the best option is to check
BitConverter.IsLittleEndian
, and compensate when necessary. For example:with: