要在c#中进行Float转换的Java字节数组

时间:2015-04-07 14:27:02

标签: java c# udp byte

通过网络从java向C#发送UDP数据包。 数据包成功收到。我在字节数组中发送一些值。 Byte数组采用Little Endian格式。所以C#可以直接读取它而无需转换为Big Endian。前2个字节是一个短值,我在C#中用

成功读取
 public short getShort(byte[] bytes,int index)
 {
    short val = BitConverter.ToInt16(bytes,index);
    return val;
}

然后有七个浮点值要读

我尝试用

阅读它们
public float floatConversion(byte[] bytes,int index)
{
    float myFloat = BitConverter.ToSingle(bytes,index);
    return myFloat;
}

但它提供了错误的值。 这是c#

的主要内容
        UdpClient client = null;
        try
        {
            client = new UdpClient(8888);
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex);
        }

        IPEndPoint server = new IPEndPoint(IPAddress.Broadcast,8888);
        byte[] packet = client.Receive(ref server);
        Console.WriteLine(packet.Length);
        Console.WriteLine(getShort(packet,0));
        Console.WriteLine(getFloat(packet, 3));
        Console.Read();

这是我从

发送数据包的java代码
 DatagramSocket socket = new DatagramSocket();
    short cc = 9999;
    float   x=66.2342f,
            y=44.6133f,
            z=99.4424f,
            rX=22.7789f,
            rY=11.9911f,
            rZ=99.1254f;
    float anim=96.1133f;
    ByteBuffer buffer =ByteBuffer.allocate(30);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.putShort(cc);
    buffer.putFloat(x);
    buffer.putFloat(y);
    buffer.putFloat(z);
    buffer.putFloat(rX);
    buffer.putFloat(rY);
    buffer.putFloat(rZ);
    buffer.putFloat(anim);
    System.out.println(buffer.array().length);
    DatagramPacket packet = new DatagramPacket(buffer.array(),buffer.array().length,InetAddress.getByName("192.168.1.2"),8888);
    socket.send(packet);

这有什么问题,我该如何解决?谢谢。

0 个答案:

没有答案