Java将负浮点数转换为字节数组

时间:2018-07-16 20:52:28

标签: java sockets floating-point type-conversion byte

我目前正在开发2D MMORPG。 所以,现在我想处理坐标,但是我有一个问题。 我需要将负浮点(坐标)转换为字节,通过套接字将其发送到服务器,然后再转换回坐标(浮点)。 我被困在这部分。

发送到服务器:

out.writeByte(packettype);
            out.writeFloat(x);
            out.writeFloat(y);
            out.flush();

向后转换:

            float x,y;
            byte[] xA = new byte[4];
            byte[] yA = new byte[4];
            for(int i=1;i<5;i++){
                xA[i-1] = (byte) b[i];
            }
            for(int i=5;i<9;i++){
                yA[i-5] = (byte) b[i];
            }


            x = ByteBuffer.wrap(xA).order(ByteOrder.BIG_ENDIAN).getFloat();
            y = ByteBuffer.wrap(yA).order(ByteOrder.BIG_ENDIAN).getFloat();

如果我的坐标小于0,我将得到如下值:

X --------- Y

2,3964 3854642970624

2,3964 2857584033792

2,3964 4395458363392

谢谢!

1 个答案:

答案 0 :(得分:0)

  

发送到服务器:

out.writeByte(packettype);
out.writeFloat(x);
out.writeFloat(y);
out.flush();

从客户端接收:

byte packettype = in.readByte();
float x = in,readFloat();
float y = in.readFloat();

...,其中inDataInputStream

相关问题