2010-03-23 8 views
9

Tengo una matriz de bytes, tamaño n, que realmente representa una matriz de tamaño n/2. Antes de escribir la matriz en un archivo de disco, necesito ajustar los valores agregando valores de polarización almacenados en otra matriz de cortos. En C++ simplemente asignaría la dirección de la matriz de bytes a un puntero para una matriz corta con un molde para abreviar y usar una aritmética de puntero o usar una unión.¿Cómo puedo acceder a una matriz de bytes como cortos en Java

¿Cómo se puede hacer esto en Java? Soy muy nuevo en Java BTW.

Respuesta

8

Puede envolver su conjunto de bytes con java.nio.ByteBuffer.

byte[] bytes = ... 
ByteBuffer buffer = ByteBuffer.wrap(bytes); 

// you may or may not need to do this 
//buffer.order(ByteOrder.BIG/LITTLE_ENDIAN); 

ShortBuffer shorts = buffer.asShortBuffer(); 

for (int i = 0, n=shorts.remaining(); i < n; ++i) { 
    final int index = shorts.position() + i; 

    // Perform your transformation 
    final short adjusted_val = shortAdjuster(shorts.get(index)); 

    // Put value at the same index 
    shorts.put(index, adjusted_val); 
} 

// bytes now contains adjusted short values 
9

Podrías hacerte el tonto, pero recomiendo echar un vistazo a las clases ByteBuffer y ShortBuffer.

byte[] arr = ... 
ByteBuffer bb = ByteBuffer.wrap(arr); // Wrapper around underlying byte[]. 
ShortBuffer sb = bb.asShortBuffer(); // Wrapper around ByteBuffer. 

// Now traverse ShortBuffer to obtain each short. 
short s1 = sb.get(); 
short s2 = sb.get(); // etc. 
+0

Gracias, usted y Alexander me han proporcionado lo que necesito. –

+1

Puede usar 'while (sb.hasRemaining())' si desea hacer un ciclo sobre todos ellos http://docs.oracle.com/javase/6/docs/api/java/nio/Buffer.html#hasRemaining() – Raekye

4

La forma correcta de hacerlo es utilizando los cambios. Entonces

for (int i = 0; i < shorts.length; i++) { 
    shorts[i] = (short)((bytes[2*i] << 8) | bytes[2*i + 1]); 
} 

Además, depende de la endianidad de la transmisión en muchos aspectos. Esto puede funcionar mejor

Cuestiones relacionadas