2010-03-23 63 views
9

我有一個字節大小爲n的數組,它實際上代表了一個大小爲n/2的數組。在將數組寫入磁盤文件之前,我需要通過添加存儲在另一個短陣列中的偏差值來調整值。在C++中,我只是將字節數組的地址分配給一個帶有強制轉換的短數組的指針,並使用指針算術或使用聯合。我怎樣才能訪問一個字節數組作爲Java中的短褲

這怎麼可能在Java中完成 - 我對Java的BTW很陌生。

回答

8

你可以用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

你可以自己動手做一下,但我建議你看看ByteBufferShortBuffer這個班。

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

謝謝,你和亞歷山大提供了我所需要的。 – 2010-03-23 19:18:26

+1

如果你想循環所有的元素,你可以使用'while(sb.hasRemaining())'http://docs.oracle.com/javase/6/docs/api/java/nio/Buffer.html#hasRemaining () – Raekye 2013-06-30 17:01:05

4

正確的做法是使用班次。因此,

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

此外,它取決於在許多方面流的endian - ness。這可能會更好

相關問題