2012-12-28 67 views
1
int port = 18000; 
DatagramSocket serverSocket = new DatagramSocket(port); 
byte[] receiveData = new byte[8]; 

System.out.println("Server Listing on Port: "+port); 
String x; 

while (true){ 
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); 
    serverSocket.receive(receivePacket); 

?? ??雙X =新Doulbe.parseBytes(recievedPacket)Java如何解析接收到的UDP字節中的double值?

+0

用'雙緩衝試試'。 –

+0

我喜歡你的實現。我自己也使用同樣的東西:p – ThePixelPony

回答

2

你可以使用ByteBuffer

Double x = ByteBuffer.wrap(receiveData).getDouble(); 
1

使用java.nio.ByteBuffer

喜歡的東西:

private static ByteBuffer buffer = ByteBuffer.allocate(8);  

public static byte[] encodeDouble(double x) { 
    buffer.clear(); 
    buffer.putDouble(0, x); 
    return buffer.array(); 
} 

public static double decodeDouble(byte[] bytes) { 
    buffer.clear(); 
    buffer.put(bytes); 
    buffer.flip(); 
    return buffer.getDouble(); 
}  
1
ByteBuffer.wrap(receiveData.getData()).getDouble(); 
0
java.io.DataInputStream.readDouble()