2012-02-19 21 views
8

Lo que trato de hacer aquí es obtener float[], convertirlo a byte[], enviarlo a través de la red como un paquete de datagramas y luego convertirlo de nuevo a a byte[] en la terminal receptora.Convierte float [] en byte [] en float [] nuevamente

Ahora sé que puedo convertir float[] en byte[] usando el método getBytes[]. Pero no sé cómo invertir la conversión.

+0

Respondió muy bien aquí: http://stackoverflow.com/a/19624671/534347 –

Respuesta

9

Creo que desee hacer uso de la clase ByteBuffer, que tiene putFloat y getFloat métodos.

+0

¡Gracias! Creo que esto es todo. Lo intentaré cuando tenga tiempo y le contaré lo que sucede. – brain56

+1

@ brain56: solo quería agregar que si está enviando esto a través de una red, querrá especificar explícitamente una codificación en lugar de dejarse a merced de la codificación predeterminada de la plataforma. –

+1

ByteBuffer también tiene el método asFloatBuffer() en caso de que no desee extraer los valores individualmente puede encadenar las llamadas al método: ByteBuffer.wrap (someByteArray) .asFloatBuffer(). Array() para pasar de un byte [] a un flotar [] –

2

Utilice Float.floatToIntBits() para extraer el valor de bit del flotador como un entero, luego use BigInteger.toByteArray() para hacer un byte[]. Esto se puede revertir utilizando el constructor BigInteger que toma un argumento byte[] y luego Float.intBitsToFloat().

5

Otra forma de usar ... ByteArrayOutputStream/DataOutputStream para la salida

float fArr[] = ...; 
ByteArrayOutputStream bas = new ByteArrayOutputStream(); 
DataOutputStream ds = new DataOutputStream(bas); 
for (float f : fArr) 
    ds.writeFloat(f); 
byte[] bytes = bas.toByteArray(); 

Uso ByteArrayInputStream/DataInputStream para la entrada

byte[] buffer = ...; 
ByteArrayInputStream bas = new ByteArrayInputStream(buffer); 
DataInputStream ds = new DataInputStream(bas); 
float[] fArr = new float[buffer.length/4]; // 4 bytes per float 
for (int i = 0; i < fArr.length; i++) 
{ 
    fArr[i] = ds.readFloat(); 
} 
+0

¿Cuál es el voto negativo de ?? – ricosrealm

+0

no existe un método como writeFloat: su código simplemente no compila – pzo

+1

gracias por señalarlo, he actualizado el código con la clase de adaptador correcta en su lugar. – ricosrealm

0

remitente:

ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 
// byteBuffer reused for every element in floatArray 
ByteBuffer byteBuffer = ByteBuffer.allocate(4); 
// go through the elements in the float array writing its 
// byte equivalent to the stream 
for(float element : floatArray) { 
    byteBuffer.clear(); 
    byteBuffer.putFloat(element) 
    byteStream.write(byteBuffer.array()); 
} 

// Logic for sending bytestream's bytes as datagram packet 
// can get byte[] from steam by: byteStream.toByteArray(); 

receptor:

ArrayList<Float> receivedValues = new ArrayList<Float>(); 
ByteBuffer byteBuffer = ByteBuffer.wrap(receivedBytes); 

// while there is still 4 bytes left on the byte buffer 
// grab the next float and add it to the received list 
int position = 0; 
while(byteBuffer.capactiy - position >= 4) { 
    receivedValues.add(byteBuffer.getFloat(position)); 
    position += 4; 
} 

float[] result = new float[receivedValues.count]; 
return receivedValues.toArray(new float[receivedValues.size()]); 
0

Es necesario utilizar el getFloat() y putFloat() comandos en el FloatBuffer del ByteBuffer. De hecho, seguramente deberías hacer esto simplemente por la gran velocidad. Y es algo grandioso de entender por manipulaciones de byte. También puede mezclar y combinar los datos, y ponerlos y obtenerlos según sea necesario. Todo está respaldado por el buffer de byte. Por lo tanto, el hecho común de enviar una matriz, también debe enviar el tamaño de la matriz.

public static void writeFloatArray(float[] array, OutputStream stream) throws IOException { 
    ByteBuffer buffer = ByteBuffer.allocate(4 * (array.length + 1)).putInt(array.length); 
    buffer.asFloatBuffer().put(array,0,array.length); 
    stream.write(buffer.array()); 
} 

Simplemente asegúrese de asignar suficientes bytes para almacenar todo en el búfer. Escribe algunas cosas, escribe otras cosas, etc. Comprender este punto hace las cosas mucho más fáciles. En el otro lado hacemos básicamente la misma cosa, aunque se requiere una lectura adicional, ya que no sabemos qué tan grande es la matriz, sólo que hay una:

public static float[] readFloatArray(InputStream in) throws IOException { 
    byte[] data = new byte[4]; 
    if (readFully(in, data) != data.length) return null; 
    int length = ByteBuffer.wrap(data).getInt(); 
    data = new byte[length * 4]; 
    if (readFully(in,data) != data.length) return null; 
    float[] array = new float[length]; 
    ByteBuffer.wrap(data).asFloatBuffer().get(array,0,array.length); 
    return array; 
} 

Y para la funcionalidad completa, aunque no exactamente parte de esta:

public static int readFully(InputStream in, byte[] data) throws IOException { 
    int offset = 0; 
    int bytesRead; 
    boolean read = false; 
    while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) { 
     read = true; 
     offset += bytesRead; 
     if (offset >= data.length) { 
      break; 
     } 
    } 
    return (read) ? offset : -1; 
}