문제

나는 할 수 있어야를 바이트 배열로 변환하여서는 기본 형식 어레이,하지만 그 대신의 캐스팅,나 말장난 유형. 정확한 용어에 대한 원시 복사지 않고 캐스팅?

나는 생각이 가능할 것여 다음을 수행 할 수 있습니다:

// 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 복사하여 컨텐츠"비트"또는"원"지만,새로 생성"보기"에서 기존의 bytebuffer.는 이유 .array() 도 실패합니다.

내가 찾아 주위에 JDK 의 원본을 발견되는 몇 가지 클래스에 의해 사용되고 있습니다 모든 이러한 버퍼 클래스고 할 필요한 것들,그러나 내부로(같은 클래스 Unsafe).

내가 생각하는 동안에는 나의 목표에 의해 얻을 수 있는 포장의 바이트 버퍼에 일 ObjectInputStream 을 읽고 기본 값 .readInt(), 에,나는 생각하는 것이 지저분하고 느리게 해결 방법입니다.

그래서,어떤 것이 있는 솔루션을 가능 을 하는 마법의 기본 형식 산수(이동 확인,엔디안,...)?

참고:나는 모두 필요 오시는 길:byte[12]->int[3],그리고 int[3]->byte[12]

도움이 되었습니까?

해결책

에 따라 javadoc,array()[1]반 버퍼의 지원 하는 배열은 배열을 지정하와 통화하여 랩()[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 바이트를 변환하기위한 그의 코드 []-> 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