2

是否可以将浮点数从大端转换为小端?我有一个来自大端平台的值,我通过UDP将其发送到 Windows 进程(小端)。这个值是一个浮点数,但是当我尝试 BitConverter.ToSingle 时,我总是得到 5.832204E-42,但它应该是 36.000。

我究竟做错了什么?

这是一段代码:

// 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;
        }
4

1 回答 1

5

36.0 和 5.832204E-42 是字节序相反的,所以这是一个字节序问题。在 Windows / .NET 上,您通常是 little-endian,所以我猜数据是 big-endian。这意味着您需要分别反转每个值的数据(而不是整个数组)。

要以 CPU 安全的方式编写此代码,最好的选择是检查BitConverter.IsLittleEndian,并在必要时进行补偿。例如:

public static float ReadSingleBigEndian(byte[] data, int offset)
{
    return ReadSingle(data, offset, false);
}
public static float ReadSingleLittleEndian(byte[] data, int offset)
{
    return ReadSingle(data, offset, true);
}
private static float ReadSingle(byte[] data, int offset, bool littleEndian)
{
    if (BitConverter.IsLittleEndian != littleEndian)
    {   // other-endian; reverse this portion of the data (4 bytes)
        byte tmp = data[offset];
        data[offset] = data[offset + 3];
        data[offset + 3] = tmp;
        tmp = data[offset + 1];
        data[offset + 1] = data[offset + 2];
        data[offset + 2] = tmp;
    }
    return BitConverter.ToSingle(data, offset);
}

和:

float x= ReadSingleBigEndian(data, 0);
float y= ReadSingleBigEndian(data, 4);
float z= ReadSingleBigEndian(data, 8);
float alpha= ReadSingleBigEndian(data, 12);
float theta= ReadSingleBigEndian(data, 16);
float phi= ReadSingleBigEndian(data, 20);
于 2012-10-24T07:36:17.583 回答