質問

私は必要な変換できるバイト配列からその他のプリミティブ型の配列での鋳造については親権者の方の同意が必要 タイプpunning. 正期の生コピーな鋳造?

と思って可能にしなければならない。

// idea: byte[12] -> int[3], and int[3] -> byte[12]

int[] ints;

ByteBuffer bb = ByteBuffer.wrap(
    new byte[]{ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3 });
IntBuffer ib = bb.asIntBuffer();

ints = ib.array(); // java.lang.UnsupportedOperationException
ints = ib.duplicate().array(); // java.lang.UnsupportedOperationException

残念ながら、この bb.asIntBuffer()ない 新しいIntBufferコピーするコンテンツ"ビット単位"または"raw"が、新たに生成しますメニューの"表示"は、既存のByteBuffer.そのた .array() は失敗します。

私は閲覧にJDKの源には、複数の授業につながることから、これらすべてのバッファラ いものが必要で、内部などのクラス Unsafe).

いと思うが、私の目標が達成される包装のbyteバッファの一部 ObjectInputStream の読み込みおよびプリミティブ値 .readInt(), 思うち、低回避策.

も他のソリューションが可能 なし う魔法のプリミティブ型演算へのチェックendians,...)?

注意:い双方向:byte[12]->int[3]、int[3]->byte[12]

役に立ちましたか?

解決

のjavadoc,array()[1]を返します現在のバッファの補助配列を配列で指定したものになりますのwrap()[2]となります。

そのため、新しい配列を作成し、ご希望のタイプです。その演算が可能で扱えるバッファ。

ByteBuffer bb = ByteBuffer.wrap(new byte[]{ 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3 });
IntBuffer ib = bb.asIntBuffer();

int[] intArray = new int[ib.limit()];
ib.get(intArray);

後退が必要で少しの計算によります。

ByteBuffer newBb = ByteBuffer.allocate(intArray.length*4);
newBb.asIntBuffer().put(intArray);
byte[] byteArray = newBb.array();

参照:

[1] http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html#array%28%29

[2] http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html#wrap%28byte[]%29

他のヒント

多くん wierob そのコードに変換するbyte[]->int[]!

今日は周辺のビットを反対方向です。

1)API

// byte[] -> int[]
public static int[] punnedToInteger(byte[] in){
    ByteBuffer bb = ByteBuffer.wrap(in);
    IntBuffer pb = bb.asIntBuffer();

    int[] out = new int[pb.limit()];
    pb.get(out);

    return out;
}

// int[] -> byte[]
public static byte[] punnedFromInteger(int[] in){
    byte[] out = new byte[in.length * Integer.SIZE / Byte.SIZE];
    ByteBuffer bb = ByteBuffer.wrap(out);

    for(int i=0; i<in.length; ++i){
        bb.putInt(in[i]);
    }

    return out;
}

2)テストケース

{
    byte[] bytes = new byte[]{ 0,0,0,1, 0,0,1,0, 0,1,0,0, 1,0,0,0 };
    int[] ints = punnedToInteger(bytes);
    System.out.println(Arrays.toString(bytes));
    System.out.println(Arrays.toString(ints));
    System.out.println();
}
{
    int[] ints = new int[]{ 1, 256, 65536, 16777216 };
    byte[] bytes = punnedFromInteger(ints);
    System.out.println(Arrays.toString(ints));
    System.out.println(Arrays.toString(bytes));
    System.out.println();
}

3)出力

[0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]
[1, 256, 65536, 16777216]

[1, 256, 65536, 16777216]
[0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top