代码之家  ›  专栏  ›  技术社区  ›  Nate Lockwood

如何在Java中访问字节数组作为短裤

  •  9
  • Nate Lockwood  · 技术社区  · 14 年前

    我有一个字节数组,大小为n,它实际上表示一个小于n/2的数组。在将数组写入磁盘文件之前,我需要通过添加存储在另一个短数组中的偏移值来调整这些值。在C++中,我只把字节数组的地址分配给一个短数组的指针,用一个简短的转换,使用指针运算或使用一个联合。

    这是如何在Java中完成的?我对Java BWT非常陌生。

    3 回复  |  直到 9 年前
        1
  •  8
  •   jox Ohad Cohen    9 年前

    您可以用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
    
        2
  •  9
  •   Adamski    14 年前

    你可以做点无聊的事,但我建议你看看 ByteBuffer 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.
    
        3
  •  4
  •   Luke Magill    14 年前

    正确的方法是使用轮班。所以

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

    而且,它在许多方面取决于流的结尾。这可能会更好